function MainApp() {

    //this.key = Cesium.BingMapsApi.defaultKey = 'AihaXS6TtE_olKOVdtkMenAMq1L5nDlnU69mRtNisz1vZavr1HhdqGRNkB2Bcqvs'; // For use with this application only

    //  this.key = Cesium.BingMapsApi.defaultKey = 'Aig5SkZ4pNMN8b4rX-RUH2c_95mK-wjb4WL9k50K51faErEGnNsxgpWHXiqS3Rhe'
    // this.key = Cesium.BingMapsApi.defaultKey = 'AiL4aYbIHjcmRrfsTZXqUbizGazb5G0VvOg6U7FvYTbqZqeMknQXTOAkgkfNv61a'

    this.pickColor = Cesium.Color.CYAN.withAlpha(0.7);
    this.plane_history_num = 0
    this.plane_fire_num = 0
    this.plane_entity
    var pathPosition = new Cesium.SampledPositionProperty();
    //当前轨迹回放的目标
    var currRailedShip
    var drawHelper
        //轨迹节点数组
    var rail_nodes
        //2维轨迹回放数组，记录多条船轨迹回放
    var replayRecordArr
        //轨迹线总长度
    var trailTime_length = 60000
    var fallow_entityPath
        //轨迹线数组
    var fallow_entityPath_arr
        //轨迹数组
    var rail_path_property
        //暂停轨迹回放、
    var shallIstopShipHistory = false
        //下面是模拟创建回放的轨迹集合
    var posArr_rail
    var limited_rail = 400
    var shapedSearch //围栏搜索
    var speed_rail = 10000; //这个速度实际是控制距离的
    var real_speed = 60; //这是真正控制回放速度的
    var stopShipHistoryPoint = -1
    var playback //轨迹回放
    var playbackball //轨迹回放
    var isOnBoat = false //看鼠标是否在船上
    var dragging = false; //拖拽标签用
    var dragging_entity
    var curr_lat
    var curr_lon
    var currcylindershipsize = { length: 1, topRadius: 0, middleRadius: 1, bottomRadius: 1 }
    var init_distance = 0
    var plane_position_list
    var myDistanceToDisplay = 5
    var particleSystem
    var swap_distance = 2000
    var longitudeString_drag
    var latitudeString_drag
    var entity_fire
    var first_qship
        //  0.0125
    var view_angle_rate = 0
    var view_angle_rate_left = 0
    var wl_lines = new Cesium.EntityCollection();

    //   var polylines = myviewer.scene.primitives.add(new Cesium.PolylineCollection());
    var MylabelsArr; //标签集合
    MylabelsArr = MylabelsArr || []

    var MylabelsLineArr; //标签连线集合
    MylabelsLineArr = MylabelsLineArr || []

    var MylabelsButtonArr; //标签按钮集合
    MylabelsButtonArr = MylabelsButtonArr || []


    var keepsizedShipArr;
    keepsizedShipArr = keepsizedShipArr || []
    var CylinderShipArr;
    CylinderShipArr = CylinderShipArr || []
    this.fallowPlane_num = 0
    this.fallowShip_num = 0
    var fallow_plane_center = new Cesium.Cartesian3();
    var hpRange = new Cesium.HeadingPitchRange();
    //  this.selectedEntity = new Map();
    this.viewer = new Cesium.Viewer('cesiumContainer', {
        scene3DOnly: false,
        selectionIndicator: true,
        baseLayerPicker: true,
        sceneMode: Cesium.SceneMode.SCENE3D
            // timeline: false
    });
    var viewModel = {
        rate: 5.0,
        gravity: 0.0,
        minimumLife: 1.0,
        maximumLife: 1.0,
        minimumSpeed: 5.0,
        maximumSpeed: 5.0,
        startScale: 1.0,
        endScale: 4.0,
        particleSize: 20.0,
        transX: 2.5,
        transY: 4.0,
        transZ: 1.0,
        heading: 0.0,
        pitch: 0.0,
        roll: 0.0,
        fly: true,
        spin: true,
        show: true
    };

    var imageryLayers = this.viewer.imageryLayers;
    var myviewer = this.viewer

    var swapedAmt = 0
        // HTML overlay for showing feature name on mouseover
    var nameOverlay = document.createElement('div');
    myviewer.container.appendChild(nameOverlay);
    nameOverlay.className = 'backdrop';
    nameOverlay.style.display = 'none';
    nameOverlay.style.position = 'absolute';
    nameOverlay.style.bottom = '0';
    nameOverlay.style.left = '0';
    nameOverlay.style['pointer-events'] = 'none';
    nameOverlay.style.padding = '4px';
    nameOverlay.style.backgroundColor = 'black';

    var currdistance = 200000
    var currRoundDistance = 200001
    var pointPrimitives = myviewer.scene.primitives.add(new Cesium.PointPrimitiveCollection());
    var polygon_billboards = myviewer.scene.primitives.add(new Cesium.BillboardCollection({ scene: myviewer.scene }));
    var fisharea
    var satelliteLayer = new Cesium.CzmlDataSource();
    // Information about the currently selected feature
    var selected = {
        feature: undefined,
        originalColor: new Cesium.Color()
    };
    // Information about the currently highlighted feature
    var highlighted = {
        feature: undefined,
        originalColor: new Cesium.Color()
    };
    var controller = myviewer.scene.screenSpaceCameraController;
    // An entity object which will hold info about the currently selected feature for infobox display
    var selectedEntity = new Cesium.Entity();
    var wl_float_lbl
    this.StopMoveFire = function(isstop) {
        myviewer.trackedEntity = undefined;

    };
    this.StartMoveFire = function(isstop) {

        myviewer.zoomTo(myviewer.entities, new Cesium.HeadingPitchRange(Cesium.Math.toRadians(-90), Cesium.Math.toRadians(-15), 7500));
        myviewer.trackedEntity = entity_fire;
    };
    this.StopMove = function(isstop) {
        myviewer.trackedEntity = undefined;

    };
    this.StartMove = function(isstop) {

        myviewer.zoomTo(myviewer.entities, new Cesium.HeadingPitchRange(Cesium.Math.toRadians(-90), Cesium.Math.toRadians(-15), 7500));
        myviewer.trackedEntity = this.plane_entity;
    };
    var label = document.getElementById("wl_lonlat_entity")
    var label_camara = document.getElementById("camera_lonlat_entity")

    this.g_ships = new Cesium.g_ships(myviewer)

    this.keepsize = new Cesium.Keepsize()
        //  CylinderShipArr
    var keepsizeug = new Cesium.KeepsizeUg()
    var keepsizeModel = new Cesium.KeepsizeModel()
    this.t_ships = new Cesium.t_ships(myviewer)
    var myPolylinesCollection = myviewer.scene.primitives.add(new Cesium.PolylineCollection());

    this.tmodel_ships = new Cesium.tmodel_ships(myviewer, myPolylinesCollection)
    var Positionarr = new Cesium.Positionarr()
    this.Viewport = new Cesium.Viewport()
    this.getCurrCameraViewPortReal = function(w, h) {

        var startCoordinates = new Cesium.Cartesian2(0, 0)
        var endCoordinates = new Cesium.Cartesian2(w, h)

        //  var endCoordinates = new Cesium.Cartesian2(myviewer.scene.canvas.width, myviewer.scene.canvas.height)
        var recobj = this.Viewport.getCurrScreenCoordinates(startCoordinates, endCoordinates, myviewer.scene)

        return recobj

    };
    var currdistance2Dparam = 2000
    this.updateShapeByDistance2D = function(width, height, left, right, curramt, distance2Dparam, twoDswap, currCamera) {
        var switchparam = 200
            // var currCamera = myviewer.scene.camera
        if (currCamera._isTwoD) {



            console.log(currCamera._currZoomAmount)
            if (currCamera._currZoomAmount > 0) {
                if (distance2Dparam <= switchparam) {


                    if (twoDswap == 0 || twoDswap == "undefined") {

                        return
                    }
                    var recobj = this.getCurrCameraViewPortReal(width, height)
                        //   while (recobj == null) {
                        //       width -= 20
                        //       height -= 20
                        //       recobj = this.getCurrCameraViewPortReal(width, height)
                        //   }
                        //
                        //  this.swaptoPolygonShip(distance2Dparam, recobj)
                    currdistance2Dparam = distance2Dparam
                    twoDswap = 0
                }
            } else if (currCamera._currZoomAmount < 0) {
                if (distance2Dparam > switchparam) {
                    // this.swaptoRoundShip(distance2Dparam)
                    // twoDswap = 1
                }
            } else if (currCamera._currZoomAmount == 0) {
                if (distance2Dparam <= switchparam) {

                    if (twoDswap == 0) {
                        return
                    }
                    var recobj = this.getCurrCameraViewPortReal(width, height)
                        //   while (recobj == null) {
                        //       width -= 20
                        //       height -= 20
                        //       recobj = this.getCurrCameraViewPortReal(width, height)
                        //   }
                        //  this.swaptoPolygonShip(distance2Dparam, recobj)
                    twoDswap = 0
                } else if (distance2Dparam > switchparam) {

                    // this.swaptoRoundShip(distance2Dparam, recobj)
                    // twoDswap = 1
                }
            }

        }

        return twoDswap

        //   var globe = myviewer.scene.globe;
        //   var leftPosition = globe.pick(left, scene);
        //   var rightPosition = globe.pick(right, scene);
        //   if (!defined(leftPosition) || !defined(rightPosition)) {
        //       viewModel.barWidth = undefined;
        //       viewModel.distanceLabel = undefined;
        //       return;
        //   }




    };
    //gps 定位
    this.getMyCurrentLocation = function() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            alert("Geolocation is not supported by this browser.");
        }
    };

    function showPosition(position) {
        alert("Latitude: " + position.coords.latitude +
            " ; Longitude: " + position.coords.longitude)
    }
    //computeViewRectangle getCurrScreenObjs
    this.getCurrCameraViewPortTest = function() {
        //
        // var w = myviewer.scene.canvas.width
        // var h = myviewer.scene.canvas.height
        // var startCoordinates = new Cesium.Cartesian2(0, 0)
        // var endCoordinates = new Cesium.Cartesian2(w, h)
        var recobj = this.Viewport.getCurrScreenObjs(myviewer.scene)

        //   while (recobj == null) {
        //       w -= 20
        //       h -= 20
        //       endCoordinates = new Cesium.Cartesian2(w, h)
        //       var recobj = this.Viewport.getCurrScreenCoordinates(startCoordinates, endCoordinates, myviewer.scene)

        //
        return recobj

    };

    this.stopLoop = function (){
        if( !myviewer.useDefaultRenderLoop){
            myviewer.useDefaultRenderLoop = true
        }
        else {
            myviewer.useDefaultRenderLoop = false
        }
        return myviewer.useDefaultRenderLoop
    };

    this.init = function() {
        shapedSearch = new Cesium.ShapeViewPortMore(this.viewer)
        myviewer.targetFrameRate =  20
        myviewer.useDefaultRenderLoop =false

        replayRecordArr = new Cesium.ReplayRecordArr()
        rail_nodes = rail_nodes || []
        fallow_entityPath_arr = fallow_entityPath_arr || []

            //轨迹回放
        real_speed = document.getElementById("select_vediospeed").value;
        playback = new Cesium.Railplayback(myviewer, real_speed, rail_nodes, pathPosition, replayRecordArr)
        playbackball = new Cesium.RailplaybackBall(myviewer, real_speed, rail_nodes, pathPosition, replayRecordArr)
            //轨迹点数
        playback.set_limited_rail(limited_rail)
        playbackball.set_limited_rail(limited_rail)
        var handler;
        var label = document.getElementById("lonlat_entity")
        var x_startmove
            //var polylines = myviewer.scene.primitives.add(new Cesium.PolylineCollection());

        //浮动标签
        var float_lbl = this.viewer.entities.add({
            label: {
                id: 'lbl_1',
                show: false,
                showBackground: true,
                font: '14px monospace',
                horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                verticalOrigin: Cesium.VerticalOrigin.TOP,
                pixelOffset: new Cesium.Cartesian2(9, 9),
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0)
                    // eyeOffset: new Cesium.Cartesian2(0, 9)
                    //  style: 'cesium-infoBox cesium-infoBox-bodyless cesium-infoBox-visible'
            }
        });
        wl_float_lbl = this.viewer.entities.add({
            label: {
                id: 'lbl_2',
                show: false,
                showBackground: true,
                font: '14px monospace',
                horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                verticalOrigin: Cesium.VerticalOrigin.TOP,
                pixelOffset: new Cesium.Cartesian2(9, 9),
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0)
                    // eyeOffset: new Cesium.Cartesian2(0, 9)
                    //  style: 'cesium-infoBox cesium-infoBox-bodyless cesium-infoBox-visible'
            }
        });
        //////
        var scene = this.viewer.scene;
        drawHelper = new Cesium.DrawHelper(this.viewer, this.viewer.scene.globe.ellipsoid);
        scene.sun.destroy();
        scene.sun = undefined;
        //'./Apps/SampleData/fire.png skybox_px.png'
        this.viewer.scene.skyBox = new Cesium.SkyBox({
            sources: {
                positiveX: './Images/skybox/bg_01.png',
                negativeX: './Images/skybox/bg_02.png',
                positiveY: './Images/skybox/bg_03.png',
                negativeY: './Images/skybox/bg_04.png',
                positiveZ: './Images/skybox/bg_05.png',
                negativeZ: './Images/skybox/bg_06.png'
            }
        });
        var cameraPosition = scene.camera.positionWC;
        var cameraDirection = scene.camera.directionWC;
        var ellipsoidPosition = scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
        var distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3()));
       // document.getElementById('wl_lonlat_entity').innerHTML = '距离地面:' + distance;
        var currshipsize = 5

        init_distance = distance;
        var currTrueDistance = distance
        var options = {};
        options.defaultResetView = Cesium.Rectangle.fromDegrees(71, 3, 90, 14);
        // Only the compass will show on the map
        options.enableCompass = true;
        options.enableZoomControls = true;
        options.enableDistanceLegend = true;
        options.enableCompassOuterRing = true;
        this.viewer.extend(Cesium.viewerCesiumNavigationMixin, options);

        //set min zoom

        // r = 2.0 * Math.max(model.boundingSphere.radius, camera.frustum.near);
        //  controller.minimumZoomDistance = 5000;

        function addAdditionalLayerOption(name, imageryProvider, alpha, show) {
            var layer = imageryLayers.addImageryProvider(imageryProvider);
            layer.alpha = Cesium.defaultValue(alpha, 0.5);
            layer.show = Cesium.defaultValue(show, true);
            layer.name = name;
            Cesium.knockout.track(layer, ['alpha', 'show', 'name']);
        }

        // var viewer = new Cesium.Viewer('cesiumContainer', {
        //     baseLayerPicker: false,
        //     imageryProvider: Cesium.createTileMapServiceImageryProvider({
        //         url : require.toUrl('http://localhost:8080/Source/Assets/Textures/NaturalEarthII')
        //     })
        // });
        /*


        */
        // // Enable lighting based on sun/moon positions
        this.viewer.scene.globe.enableLighting = false;
        //   var widget = new Cesium.CesiumWidget('cesiumContainer'); //定义一个地球容器
        //viewer.extend(Cesium.viewerCesiumNavigationMixin, {});
        //   var cesiumWidget = new Cesium.CesiumWidget('cesiumContainer');
        var url = 'http://115.28.101.41:8088/geoserver/cite/wms'; //Geoserver URL //wms引用的地址，可以在wms服务打开的页面的源代码中找到
        // this.strImgUrl = "http://localhost:8092/MSAChartImages/";
        //this.strImgUrl = "http://www.yimasoftdemo.cc:800/MSAChartImages/";
        //API_SetMapImagesUrl("http://www.yimasoftdemo.cc:800/mapimg/");
        url = 'http://127.0.0.1:8088/geoserver/test/wms?service=WMS&version=1.1.0&request=GetMap&layers=test:World_Country&styles=&bbox=-180.0,-59.48429489135745,180.00000000000003,83.62741851000004&width=768&height=330&srs=EPSG:4326&format=application/openlayers#toggle'
            //this.strImgUrl = "http://www.yimasoftdemo.cc:800/MSAChartImages/";
            //API_SetMapImagesUrl("http://www.yimasoftdemo.cc:800/mapimg/");
            // url = "http://localhost:8092/MSAChartImages/";
            // url = "../images/MSAChartImages/"
            // url: "/proxy/http://127.0.0.1:8088/geoserver/test/wms?service=WMS&version=1.1.0&request=GetMap&layers=test:World_Country&styles=&bbox=-180.0,-59.48429489135745,180.00000000000003,83.62741851000004&width=768&height=330&srs=EPSG:4326&format=application/openlayers#toggle",
            //url = '/proxy/http://www.yimasoftdemo.cc:800/mapimg/'
            // url = 'http://www.yimasoftdemo.cc:800/mapimg/'
        url = 'https://dev.virtualearth.net'

        var layers = this.viewer.scene.globe.imageryLayers;



        // var label_googleSource = new Cesium.UrlTemplateImageryProvider({
        //     //  url: 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
        //     // url: "http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
        //     // url: 'http://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7',

        //     url: 'http://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
        //     // url: "https://services.arcgisonline.com/arcgis/rest/services/Demographics/china_Population_Density/MapServer/WMTS/",
        //     //    url: "http://webst01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8",
        //     // layer: "tdtVecBasicLayer",
        //     // style: "default",
        //     // format: "image/jpeg",
        //     // show: false
        // });
        // layers.addImageryProvider(label_googleSource);
        var layers = this.viewer.scene.globe.imageryLayers;

        // var label_gd = new Cesium.UrlTemplateImageryProvider({
        //     url: 'http://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7',
        // });
        // layers.addImageryProvider(label_gd);
        // var label_googleSource2 = new Cesium.WebMapTileServiceImageryProvider({
        //     //url: '../../vt/imgtp=png32&lyrs=h@365000000&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&s=Galil',
        //     url: "http://t1.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}",
        //     // url: "http://t1.tianditu.com/DataServer?T=vec_w&X={x}&Y={y}&L={z}",
        //     credit: ''
        // });
        // layers.addImageryProvider(label_googleSource2);
//天地图
        // var label_googleSource3 = new Cesium.WebMapTileServiceImageryProvider({
        //     //  url: 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
        //     url: "http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
        //     //url: "https://services.arcgisonline.com/arcgis/rest/services/Demographics/USA_Population_Density/MapServer/WMTS/",
        //     layer: "tdtVecBasicLayer",
        //     style: "default",
        //     format: "image/jpeg",
        //     show: false
        // });
       //  layers.addImageryProvider(label_googleSource3);
       /*
       1.天地图项目形式，天地图（郭嘉对）项目在更新的过程中是以政府项目形式层级往外投标（地级市有地级市，县级市有县级市）。这样做的结果就是数据来源是当地政府及其业务相关企业提供的。2.数据来源。扯出第二个话题，天地项目数据来源于各地政府汇总，而数据很可能来自于当地测绘公司、不动产、以及规划局、水利局、林业局等数据，数据的精确程度是非常值得信任的。拿房屋来说，还有任何数据能比不动产坐标更准吗？村界等境界线其他商业地图永远也不可能有天地图准确。天地图放大到一定级别，房屋边界线（矢量）很清晰，商业地图永远也不可能有这样的水平。

作者：匿名用户
链接：https://www.zhihu.com/question/22405962/answer/267955729
来源：知乎
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
       */
       //天地图
        var label_googleSource4 = new Cesium.WebMapTileServiceImageryProvider({
            //  url: 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
            url: "http://t0.tianditu.com/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
            //url: "https://services.arcgisonline.com/arcgis/rest/services/Demographics/USA_Population_Density/MapServer/WMTS/",
            layer: "tdtAnnoLayer",
            style: "default",
            format: "image/jpeg",
            show: false
        });
        layers.addImageryProvider(label_googleSource4);

        //高德地图
        // var label_gd = new Cesium.UrlTemplateImageryProvider({
        //     url: "http://wprd2.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7",
        // });
        //  layers.addImageryProvider(label_gd);
        //add heater
        //"options.bounds.north, bounds.south, bounds.east and bounds.west are required."
        // var heatMap = new Cesium.HeatmapImageryProvider({
        //         bounds: { "north": 500, "south": 500, "east": 500, "west": 500 },
        //         //  gradient: { 0.25: "rgb(0,0,255)", 0.55: "rgb(0,255,0)", 0.85: "yellow", 1.0: "rgb(255,0,0)" },
        //         // width: 100,
        //         // height: 100,
        //         // radius: 300,
        //         data: { "min": 0, "max": 200, "points": { "x": 147.1383883832, "y": -41.4358733544, "value": 82 } }
        //         //  data: [{ "x": 147.1383442264, "y": -41.4360048372, "value": 76 }, { "x": 147.1384363011, "y": -41.4360298848, "value": 63 }, { "x": 147.138368102, "y": -41.4358360603, "value": 1 }, { "x": 147.1385627739, "y": -41.4358799123, "value": 21 }, { "x": 147.1385138501, "y": -41.4359327669, "value": 28 }, { "x": 147.1385031219, "y": -41.4359730105, "value": 41 }, { "x": 147.1384127393, "y": -41.435928255, "value": 75 }, { "x": 147.1384551136, "y": -41.4359450132, "value": 3 }, { "x": 147.1384927196, "y": -41.4359158649, "value": 45 }, { "x": 147.1384938639, "y": -41.4358498311, "value": 45 }, { "x": 147.1385183299, "y": -41.4360213794, "value": 93 }, { "x": 147.1384007925, "y": -41.4359860133, "value": 46 }, { "x": 147.1383604844, "y": -41.4358298672, "value": 54 }, { "x": 147.13851025, "y": -41.4359098303, "value": 39 }, { "x": 147.1383874733, "y": -41.4358511035, "value": 34 }, { "x": 147.1384981796, "y": -41.4359355403, "value": 81 }, { "x": 147.1384504107, "y": -41.4360332348, "value": 39 }, { "x": 147.1385582664, "y": -41.4359788335, "value": 20 }, { "x": 147.1383967364, "y": -41.4360581999, "value": 35 }, { "x": 147.1383839615, "y": -41.436016316, "value": 47 }, { "x": 147.1384082712, "y": -41.4358423338, "value": 36 }, { "x": 147.1385092651, "y": -41.4358577623, "value": 69 }, { "x": 147.138360356, "y": -41.436046789, "value": 90 }, { "x": 147.138471893, "y": -41.4359184292, "value": 88 }, { "x": 147.1385605689, "y": -41.4360271359, "value": 81 }, { "x": 147.1383585714, "y": -41.4359362476, "value": 32 }, { "x": 147.1384939114, "y": -41.4358844253, "value": 67 }, { "x": 147.138466724, "y": -41.436019121, "value": 17 }, { "x": 147.1385504355, "y": -41.4360614056, "value": 49 }, { "x": 147.1383883832, "y": -41.4358733544, "value": 82 }, { "x": 147.1385670669, "y": -41.4359650236, "value": 25 }, { "x": 147.1383416534, "y": -41.4359310876, "value": 82 }, { "x": 147.138525285, "y": -41.4359394661, "value": 66 }, { "x": 147.1385487719, "y": -41.4360137656, "value": 73 }, { "x": 147.1385496029, "y": -41.4359187277, "value": 73 }, { "x": 147.1383989222, "y": -41.4358556562, "value": 61 }, { "x": 147.1385499424, "y": -41.4359149305, "value": 67 }, { "x": 147.138404523, "y": -41.4359563326, "value": 90 }, { "x": 147.1383883675, "y": -41.4359794855, "value": 78 }, { "x": 147.1383967187, "y": -41.435891185, "value": 15 }, { "x": 147.1384610005, "y": -41.4359044797, "value": 15 }, { "x": 147.1384688489, "y": -41.4360396127, "value": 91 }, { "x": 147.1384431875, "y": -41.4360684409, "value": 8 }, { "x": 147.1385411067, "y": -41.4360645847, "value": 42 }, { "x": 147.1385237178, "y": -41.4358843181, "value": 31 }, { "x": 147.1384406464, "y": -41.4360003831, "value": 51 }, { "x": 147.1384679169, "y": -41.4359950456, "value": 96 }, { "x": 147.1384194314, "y": -41.4358419739, "value": 22 }, { "x": 147.1385049792, "y": -41.4359574813, "value": 44 }, { "x": 147.1384097378, "y": -41.4358598672, "value": 82 }, { "x": 147.1384993219, "y": -41.4360352975, "value": 84 }, { "x": 147.1383640499, "y": -41.4359839518, "value": 81 }]
        //     })
        //     // let data = [{ "x": 147.1383442264, "y": -41.4360048372, "value": 76 }, { "x": 147.1384363011, "y": -41.4360298848, "value": 63 }, { "x": 147.138368102, "y": -41.4358360603, "value": 1 }, { "x": 147.1385627739, "y": -41.4358799123, "value": 21 }, { "x": 147.1385138501, "y": -41.4359327669, "value": 28 }, { "x": 147.1385031219, "y": -41.4359730105, "value": 41 }, { "x": 147.1384127393, "y": -41.435928255, "value": 75 }, { "x": 147.1384551136, "y": -41.4359450132, "value": 3 }, { "x": 147.1384927196, "y": -41.4359158649, "value": 45 }, { "x": 147.1384938639, "y": -41.4358498311, "value": 45 }, { "x": 147.1385183299, "y": -41.4360213794, "value": 93 }, { "x": 147.1384007925, "y": -41.4359860133, "value": 46 }, { "x": 147.1383604844, "y": -41.4358298672, "value": 54 }, { "x": 147.13851025, "y": -41.4359098303, "value": 39 }, { "x": 147.1383874733, "y": -41.4358511035, "value": 34 }, { "x": 147.1384981796, "y": -41.4359355403, "value": 81 }, { "x": 147.1384504107, "y": -41.4360332348, "value": 39 }, { "x": 147.1385582664, "y": -41.4359788335, "value": 20 }, { "x": 147.1383967364, "y": -41.4360581999, "value": 35 }, { "x": 147.1383839615, "y": -41.436016316, "value": 47 }, { "x": 147.1384082712, "y": -41.4358423338, "value": 36 }, { "x": 147.1385092651, "y": -41.4358577623, "value": 69 }, { "x": 147.138360356, "y": -41.436046789, "value": 90 }, { "x": 147.138471893, "y": -41.4359184292, "value": 88 }, { "x": 147.1385605689, "y": -41.4360271359, "value": 81 }, { "x": 147.1383585714, "y": -41.4359362476, "value": 32 }, { "x": 147.1384939114, "y": -41.4358844253, "value": 67 }, { "x": 147.138466724, "y": -41.436019121, "value": 17 }, { "x": 147.1385504355, "y": -41.4360614056, "value": 49 }, { "x": 147.1383883832, "y": -41.4358733544, "value": 82 }, { "x": 147.1385670669, "y": -41.4359650236, "value": 25 }, { "x": 147.1383416534, "y": -41.4359310876, "value": 82 }, { "x": 147.138525285, "y": -41.4359394661, "value": 66 }, { "x": 147.1385487719, "y": -41.4360137656, "value": 73 }, { "x": 147.1385496029, "y": -41.4359187277, "value": 73 }, { "x": 147.1383989222, "y": -41.4358556562, "value": 61 }, { "x": 147.1385499424, "y": -41.4359149305, "value": 67 }, { "x": 147.138404523, "y": -41.4359563326, "value": 90 }, { "x": 147.1383883675, "y": -41.4359794855, "value": 78 }, { "x": 147.1383967187, "y": -41.435891185, "value": 15 }, { "x": 147.1384610005, "y": -41.4359044797, "value": 15 }, { "x": 147.1384688489, "y": -41.4360396127, "value": 91 }, { "x": 147.1384431875, "y": -41.4360684409, "value": 8 }, { "x": 147.1385411067, "y": -41.4360645847, "value": 42 }, { "x": 147.1385237178, "y": -41.4358843181, "value": 31 }, { "x": 147.1384406464, "y": -41.4360003831, "value": 51 }, { "x": 147.1384679169, "y": -41.4359950456, "value": 96 }, { "x": 147.1384194314, "y": -41.4358419739, "value": 22 }, { "x": 147.1385049792, "y": -41.4359574813, "value": 44 }, { "x": 147.1384097378, "y": -41.4358598672, "value": 82 }, { "x": 147.1384993219, "y": -41.4360352975, "value": 84 }, { "x": 147.1383640499, "y": -41.4359839518, "value": 81 }];
        //     // let valueMin = 0;
        //     // let valueMax = 100;

        // // add data to heatmap
        // // heatMap.setWGS84Data(valueMin, valueMax, data);
        // layers.addImageryProvider(heatMap);
        // var blackMarble = layers.addImageryProvider(new Cesium.WebMapServiceImageryProvider({ //加载一个wms服务的图层覆盖到地球上
        //     url: url,
        //     layers: 'cite:', // Here just give layer name  //通过onclick＝“showEarth（year）”获取year的值传进来，从而得到不同年份的图层
        //     version: '1.1.0' //wms服务版本号
        // }));
        //  addAdditionalLayerOption('Grid', new Cesium.GridImageryProvider(), 1.0, false);
        // Load STK World Terrain 地图加载关键部位
        // this.viewer.terrainProvider = new Cesium.GeoserverTerrainProvider({
        //     url: "http://www.yimasoftdemo.cc:800/mapimg/",
        //     layerName: "SRTM90",
        //     styleName: "grayToColor",
        //     waterMask: true
        // });
        // this.viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
        //     // 'https://assets.agi.com/stk-terrain/world',
        //     // url: 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
        //     url: "http://www.yimasoftdemo.cc:800/mapimg/",
        //     // url = 'http://www.yimasoftdemo.cc:800/mapimg/',
        //     // url: '../CesiumUnminified/Assets/imagery/NaturalEarthII',
        //     requestWaterMask: true, // required for water effects
        //     requestVertexNormals: false // required for terrain lighting
        // });

        // this.viewer.terrainProvider = new Cesium.BingMapsImageryProvider({
        //     url: "http://www.yimasoftdemo.cc:800/mapimg/"

        // });
        this.kmlOptions = {
            camera: this.viewer.scene.camera,
            canvas: this.viewer.scene.canvas,
            clampToGround: true
        };


        var highlightColor = Cesium.Color.RED.withAlpha(0.6);
        var normalColor = Cesium.Color.YELLOW.withAlpha(0.6);
        var previousPickedEntity = undefined;

        handler = new Cesium.ScreenSpaceEventHandler(myviewer.canvas);


        handler.setInputAction(function(movement) {

            cameraPosition = scene.camera.positionWC;
            cameraDirection = scene.camera.directionWC;
            var xrate = Math.abs(cameraDirection.x)
            ellipsoidPosition = scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
            distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3())) /
                xrate;

            currTrueDistance = distance
                //  document.getElementById('wl_lonlat_entity').innerHTML = '距离地面:' + myviewer.scene.camera.frustum.right;
                //下面计算2D情况下地图比例
            if (myviewer.scene._frameState.mode == 2) {
                var left_right_distance = myviewer.scene.camera.frustum.right - myviewer.scene.camera.frustum.left;
                var pixelDistance = left_right_distance / myviewer.canvas.clientWidth
                document.getElementById('wl_lonlat_entity').innerHTML = '2D比例 1:' + Math.round(pixelDistance, 2) + ' km'
            } else {
                document.getElementById('wl_lonlat_entity').innerHTML = ''
            }

            // var iszoomOut = false
            // if (distance > init_distance) {
            //     iszoomOut = true
            // } else if (distance < init_distance) {
            //     iszoomOut = false
            // }


            // init_distance = distance



        }, Cesium.ScreenSpaceEventType.RIGHT_UP);
        //MIDDLE_UP
        handler.setInputAction(function(MIDDLE_UP) {

            cameraPosition = scene.camera.positionWC;
            cameraDirection = scene.camera.directionWC;
            var xrate = Math.abs(cameraDirection.x)
            ellipsoidPosition = scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
            distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3())) /
                xrate;
            // alert(distance)
            currTrueDistance = distance
           // document.getElementById('wl_lonlat_entity').innerHTML = '距离地面:' + distance;


            var iszoomOut = false
            if (distance > init_distance) {
                iszoomOut = true
            } else if (distance < init_distance) {
                iszoomOut = false
            }
            // currcylindershipsize = keepsizeug.adjustSize(distance, init_distance)
            // alert(currcylindershipsize)

            //  keepsizeug.changeCylinderShipSize(currcylindershipsize, myviewer.scene.globe.ellipsoid, iszoomOut, distance, CylinderShipArr)
            init_distance = distance

        }, Cesium.ScreenSpaceEventType.WHEEL);


        // handler.setInputAction(function(movement) {

        // }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
        handler.setInputAction(function(movement) {

        }, Cesium.ScreenSpaceEventType.MIDDLE_DOWN);

        /*
          this.getcoordinatesv2 = function() {

                //iScrnPoX, iScrnPoY, scale
                // Output the window position of longitude/latitude (0, 0) every time the mouse moves.
                var scene = myviewer.scene;
                var ellipsoid = myviewer.scene.globe.ellipsoid;
                var position = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
                var handler = new Cesium.ScreenSpaceEventHandler(myviewer.scene.canvas);
                handler.setInputAction(function(movement) {
                    console.log(Cesium.SceneTransforms.wgs84ToWindowCoordinates(scene, position));
                }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            };
        */
        //报错和下面关系大！！！！
        /*
        An error occurred while rendering. Rendering has stopped.
        RangeError: Invalid array length
        RangeError: Invalid array length
        */
        //报错和下面关系大！！！！
        handler.setInputAction(
            function(click) {

                debugger
                var descrarr = []

                var pickedObject = scene.pick(click.position);
                //世界坐标转屏幕坐标 设法求出标签移动后的屏幕坐标
                //Cesium.SceneTransforms.wgs84ToWindowCoordinates(scene, Cartesian3);
                if (!Cesium.defined(pickedObject)) {
                    return;
                }
                //&& !Cesium.defined(dragging_entity.cylinder)
                if (typeof(pickedObject.id) != 'string') {



                    isOnBoat = false
                    dragging = true;
                    dragging_entity = pickedObject.id
                    if (Cesium.defined(pickedObject.primitive.type)) {

                        // myviewer.scene.primitives.add(pickedObject.primitive)
                        return
                    }
                    if (Cesium.defined(dragging_entity)) {
                        if (Cesium.defined(dragging_entity.billboard)) {


                            for (var t = 0; t < MylabelsButtonArr.length; t++) {
                                var npin = MylabelsButtonArr[t]

                                if (npin.name == dragging_entity._name) {

                                    for (var t1 = 0; t1 < MylabelsArr.length; t1++) {
                                        if (npin.name == 'btn' + MylabelsArr[t1]._name) {
                                            myviewer.entities.remove(MylabelsButtonArr[t1])
                                            myviewer.entities.remove(MylabelsArr[t1])
                                            myviewer.entities.remove(MylabelsLineArr[t1].line)
                                            MylabelsButtonArr.splice(t1, 1)
                                            MylabelsArr.splice(t1, 1)
                                            MylabelsLineArr.splice(t1, 1)

                                        }
                                    }

                                    return
                                }
                            }
                        }
                    }

                    myviewer.scene.screenSpaceCameraController.enableRotate = false;
                    return;
                }
                //测试此处返回
                // return

                descrarr = pickedObject.primitive._descr.split(';')
                if (descrarr.length > 0) {
                  //  selectedEntity.description = ' <div class="cesium-infoBox-loading"></div>';
                    if (descrarr.length >= 3) {

                        var mypos = pickedObject.primitive._actualPosition
                        if (Cesium.defined(mypos)) {
                            //报错和下面关系大！！！！
                            /*
                            An error occurred while rendering. Rendering has stopped.
                            RangeError: Invalid array length
                            RangeError: Invalid array length
                            */
                            //报错和下面关系大！！！！
                            var vp = new Cesium.Viewport()
                            var find = vp.inViewUg(mypos, myviewer.camera)

                            if (find) {

                                selectedEntity.description  = '<table class="cesium-infoBox-defaultTable"><tbody>' +
                                    '<tr><th>信息:</th><td>' + descrarr[0] + '</td></tr>' +
                                    '<tr><th>信息:</th><td>' + descrarr[1] + '</td></tr>' +
                                    '<tr><th>信息:</th><td>' + descrarr[2] + '</td></tr>' +
                                    '<tr><th>信息:</th><td>' + descrarr[3] + '</td></tr>' +
                                    '</tbody></table>';
                                curr_lon = descrarr[1]
                                curr_lat = descrarr[2]
                                isOnBoat = true
                                dragging = true;
                            }
                        } else {

                            curr_lon = descrarr[1]
                            curr_lat = descrarr[2]
                        }
                    }


                }
                document.getElementById('ShowDetailShipInfoDiv').style.display = "block"
                document.getElementById('ShowShipId').value = descrarr[0]
                document.getElementById('ship_lon').value = descrarr[1]
                document.getElementById('ship_lat').value = descrarr[2]
                document.getElementById('ship_rotation').value = descrarr[3]

debugger
                //ShowShipDetailInfo from YimaIncDemo.js
                var iShipId = descrarr[0]
                ShowShipDetailInfo(iShipId, iShipId,
                    descrarr[1], descrarr[2],
                    bSelPlayTrackShip, click.position, pickedObject.primitive._sponser); //目标
                for (var t = 0; t < MylabelsArr.length; t++) {
                    var npin = MylabelsArr[t]
                        // if (npin.id == descrarr[0]) {
                    if (npin.name == descrarr[0]) {

                        //表明标签已添加过，不必再添加
                        isOnBoat = false
                        dragging = true;
                        dragging_entity = npin
                            // alert(dragging_entity.name)
                        myviewer.scene.screenSpaceCameraController.enableRotate = false;
                        //此处先获取当前经纬度  curr_lon    curr_lat
                        //   pinBuilderl.handleMouseDown(click)
                        return
                    }
                }


                //报错和下面关系大！！！！CLAMP_TO_GROUND
                /*
                An error occurred while rendering. Rendering has stopped.
                RangeError: Invalid array length
                RangeError: Invalid array length
                */
                //报错和下面关系大！！！！ CLAMP_TO_GROUND
                if (!Cesium.defined(curr_lon)) {
                    console.log('经纬度坐标不能为空')
                    return
                }
                if (nameOverlay.textContent == "无选中目标") {
                    console.log('无选中目标')
                    return
                }

                //下面是可拖动标签部分
                // var pinBuilderButton = new Cesium.PinBuilderButton(300);

                // var pinButton = myviewer.entities.add({
                //     name: 'btn' + descrarr[0],
                //     position: Cesium.Cartesian3.fromDegrees(curr_lon, curr_lat, 0),
                //     heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //     billboard: {
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //         // image: pinBuilder.fromText(descrarr[0] + '\n' + descrarr[1].substring(0, 10), Cesium.Color.SALMON, 300),
                //         image: pinBuilderButton.fromText(Cesium.Color.SALMON, 300),
                //         //  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,

                //     }

                // });
                // MylabelsButtonArr.push(pinButton)

                // var pinBuilderl = new Cesium.PinBuilderLabel(300);
                // var url = Cesium.buildModuleUrl('Assets/Textures/maki/grocery.png');
                // var pin = myviewer.entities.add({
                //     name: descrarr[0],
                //     position: Cesium.Cartesian3.fromDegrees(curr_lon, curr_lat, 0),
                //     heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                //     billboard: {
                //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,

                //         //标签文字描述  在此
                //         image: pinBuilderl.fromText(url, descrarr[0] + '\n' + descrarr[1] + '\n' + descrarr[2], Cesium.Color.SALMON, 300),

                //         // image: pinBuilderl.fromText(url, descrarr[0] + '\n' + descrarr[1] + '\n' + descrarr[2] + '\n' + '船国家:香港' + '\n' + '船类型:货船' + '\n' + 'test:test' + '\n' + 'test:test2' + '\n' + 'test:test3', Cesium.Color.SALMON, 300),
                //         //  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,

                //     }

                // });

                // //如curr_lon为空，恐会引起报错  descrarr[1] descrarr[2]
                // longitudeString_drag = descrarr[1]
                // latitudeString_drag = descrarr[2]

                // MylabelsArr.push(pin)



                // var blueLine = myviewer.entities.add({
                //     name: descrarr[0],
                //     polyline: {
                //         positions: Cesium.Cartesian3.fromDegreesArrayHeights([curr_lon, curr_lat, 0, curr_lon, curr_lat, 0]),
                //         width: 2,
                //         material: Cesium.Color.SALMON

                //     }
                // });
                // var fullLine = { 'line': blueLine, 'orig_x': curr_lon, 'orig_y': curr_lat }

                // MylabelsLineArr.push(fullLine)
                dragging = false;
                isOnBoat = false


            },
            Cesium.ScreenSpaceEventType.LEFT_DOWN
        );
        //设法添加关闭按钮

        handler.setInputAction(function(movement) {
            // return

            var entitytype
            var pickedPrimitive = scene.pick(movement.endPosition);
            //  for model start
            //
            var primitive_model;
            // if (Cesium.defined(pickedPrimitive)) {
            //     primitive_model = pickedPrimitive.primitive;
            //     if (primitive_model instanceof Cesium.Model) {

            //         nameOverlay.textContent = '目标!！' + primitive_model.id;
            //     }
            // }


            //   for model end
            if (Cesium.defined(pickedPrimitive)) {

                entitytype = pickedPrimitive.primitive._entitytype
                if (!Cesium.defined(entitytype)) {
                    return
                }
                if (entitytype.toString().indexOf('物标') > 0) {
                    label.textContent = entitytype
                    return
                }
            }
            var pickedEntity = (Cesium.defined(pickedPrimitive)) ? pickedPrimitive.id : undefined;

            if (Cesium.defined(pickedEntity)) {
                //pickedPrimitive.billboard.scale = 2.0;
                if (typeof(pickedPrimitive.id.cylinder) !== "undefined") {


                    nameOverlay.textContent = pickedPrimitive.id._name
                        //   selectedEntity.name = pickedPrimitive.id._name;
                    myviewer.selectedEntity = selectedEntity;

                }
                if (typeof(pickedEntity._description) !== "undefined") {


                    nameOverlay.textContent = pickedEntity._description +
                        ';航速:' + pickedEntity._speed +
                        ';航向:' + pickedEntity._direction +
                        ';经度:' + pickedEntity._x +
                        ';纬度:' + pickedEntity._y
                    selectedEntity.name = pickedEntity._description


                }
                if (typeof(pickedPrimitive.id._point) !== "undefined") {
                    //  pickedPrimitive.id._point._color._value = highlightColor;
                    try {
                        pickedPrimitive.id._point._outlineColor._value = highlightColor;


                        pickedPrimitive.id._point._outlineWidth._value = 8;

                        previousPickedEntity = pickedPrimitive;
                    } catch (e) {}

                }

            }
            //  this.getCurrCameraViewPort()

            var cartesian = scene.camera.pickEllipsoid(movement.endPosition, scene.globe.ellipsoid);
            //  console.log('cartesian position:' + cartesian)
            if (cartesian) {
                var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                var longitudeString = Cesium.Math.toDegrees(cartographic.longitude).toFixed(2);
                var latitudeString = Cesium.Math.toDegrees(cartographic.latitude).toFixed(2);

                //此处也能实时获取移动后经纬度
                longitudeString_drag = Cesium.Math.toDegrees(cartographic.longitude);
                latitudeString_drag = Cesium.Math.toDegrees(cartographic.latitude);
                // label.textContent =
                //     '经度: ' + ('   ' + longitudeString).slice(-7) + '\u00B0' +
                //     '\n纬度: ' + ('   ' + latitudeString).slice(-7) + '\u00B0';
                label.textContent =
                    '经度: ' + ('' + longitudeString_drag) + '\u00B0' +
                    '\n纬度: ' + ('' + latitudeString_drag) + '\u00B0';
            } else {
                float_lbl.label.show = false;
                label.textContent = ""
            }
            if (typeof(pickedEntity) == "undefined") {
                float_lbl.label.show = false;
            }


            if (Cesium.defined(highlighted.feature)) {
                highlighted.feature.color = highlighted.originalColor;
                highlighted.feature = undefined;
            }

            // Pick a new feature
            var pickedFeature = myviewer.scene.pick(movement.endPosition);
            if (!Cesium.defined(pickedFeature)) {
                nameOverlay.style.display = 'none';
                return;
            }
            //////
            if (pickedFeature === highlighted.feature) {
                Cesium.Color.clone(highlighted.originalColor, selected.originalColor);
                highlighted.feature = undefined;
            } else {
                Cesium.Color.clone(pickedFeature.color, selected.originalColor);
            }

            nameOverlay.style.display = 'block';
            nameOverlay.style.bottom = myviewer.canvas.clientHeight - movement.endPosition.y + 'px';
            nameOverlay.style.left = movement.endPosition.x + 'px';


            try {
                 
                if (typeof(pickedFeature.primitive._descr) !== undefined) {
                    // console.log(JSON.stringify(pickedFeature.descr))
                    if (pickedFeature.primitive._descr.indexOf('undefined') < 0) {
                        var muycurrDistance = document.getElementsByClassName('distance-legend-label')[0].innerHTML
                        if (pickedFeature.primitive._descr.indexOf("simpleship") >= 0) {



                            if (muycurrDistance.indexOf('km' > 0)) {
                                var tt = Number(muycurrDistance.replace("km", ""))
                                if (tt >= myDistanceToDisplay) {
                                    nameOverlay.textContent = pickedFeature.primitive.alarmmsg+';选中目标！！' + pickedFeature.primitive._descr;
                                    selectedEntity.name =pickedFeature.primitive.alarmmsg+ pickedFeature.primitive._descr;

                                } else {
                                    // nameOverlay.textContent = pickedFeature.descr
                                    nameOverlay.textContent = ''

                                    //  selectedEntity.name = ""
                                }
                            } else {

                                nameOverlay.textContent = ""

                            }

                        } else {


                            if (muycurrDistance.indexOf('km' > 0)) {
                                var tt = Number(muycurrDistance.replace("km", ""))
                                if (tt <= myDistanceToDisplay) {
                                    if (pickedFeature.primitive._descr.indexOf('flexship') >= 0) {
                                        nameOverlay.textContent =pickedFeature.primitive.alarmmsg +';选中目标！-' + pickedFeature.primitive._descr;
                                        selectedEntity.name =pickedFeature.primitive.alarmmsg + pickedFeature.primitive._descr;
                                    } else {
                                        nameOverlay.textContent = "无选中目标"
                                    }

                                } else {
                                    if (muycurrDistance.indexOf('km') < 0 && muycurrDistance.indexOf('m') > 0 &&
                                        pickedFeature.primitive._descr.indexOf('roundobj') >= 0) {
                                        //do nothing
                                        nameOverlay.textContent = '无选中目标';

                                    } else {

                                        nameOverlay.textContent =pickedFeature.primitive.alarmmsg+ ';选中目标**！--' + pickedFeature.primitive._descr;
                                        selectedEntity.name =pickedFeature.primitive.alarmmsg+ pickedFeature.primitive._descr;
                                    }

                                }
                            } else {
                                if (muycurrDistance.indexOf('km' <= 0) && muycurrDistance.indexOf('m' > 0)) {
                                    if (pickedFeature.primitive._descr.indexOf('flexship') >= 0) {
                                        nameOverlay.textContent = pickedFeature.primitive.alarmmsg +';选中目标！---' + pickedFeature._descr;
                                        selectedEntity.name =pickedFeature.primitive.alarmmsg + pickedFeature._descr;
                                    } else {
                                        nameOverlay.textContent = "无选中目标--"
                                    }
                                }
                            }
                        }
                    }

                    var descrarr = []

                    descrarr = pickedFeature.primitive._descr.split(';')
                    if (descrarr.length > 0) {
                      //  selectedEntity.description = ' <div class="cesium-infoBox-loading"></div>';
                       selectedEntity.description = '';
                        if (descrarr.length >= 3) {

                            var mypos = pickedFeature.primitive._actualPosition
                                //报错和下面关系大！！！！
                                /*
                                An error occurred while rendering. Rendering has stopped.
                                RangeError: Invalid array length
                                RangeError: Invalid array length
                                */
                                //报错和下面关系大！！！！
                            if (Cesium.defined(mypos)) {
                                var vp = new Cesium.Viewport()
                                var find = vp.inViewUg(mypos, myviewer.camera)
                                if (find) {
                                     // +
                                    selectedEntity.description  = '<table class="cesium-infoBox-defaultTable"><tbody>' +
                                        '<tr><th>状态:</th><td>' + pickedFeature.primitive.alarmmsg + '</td></tr>' +
                                        '<tr><th>操作人:</th><td>' + pickedFeature.primitive.sponser + '</td></tr>' +
                                        '<tr><th>序列号:</th><td>' + descrarr[0] + '</td></tr>' +
                                        '<tr><th>经度:</th><td>' + descrarr[1] + '</td></tr>' +
                                        '<tr><th>纬度:</th><td>' + descrarr[2] + '</td></tr>' +
                                        '</tbody></table>';


                                }
                            }


                        }

                    }

                    myviewer.selectedEntity = selectedEntity;

                }
            } catch (e) {}
            if (dragging) {
                if (typeof dragging_entity === 'undefined' || dragging_entity === null) {
                    // Do stuff
                    return
                }
                var cartesian = dragging_entity.position.getValue(Cesium.JulianDate.fromDate(new Date()));
                //
                var cartographic = scene.globe.ellipsoid.cartesianToCartographic(cartesian);
                var surfaceNormal = scene.globe.ellipsoid.geodeticSurfaceNormal(cartesian);
                var planeNormal = Cesium.Cartesian3.subtract(scene.camera.position, cartesian, new Cesium.Cartesian3());
                planeNormal = Cesium.Cartesian3.normalize(planeNormal, planeNormal);
                var ray = myviewer.scene.camera.getPickRay(movement.endPosition);
                var plane = Cesium.Plane.fromPointNormal(cartesian, planeNormal);

                var newCartesian = Cesium.IntersectionTests.rayPlane(ray, plane);

                var newCartographic = scene.globe.ellipsoid.cartesianToCartographic(newCartesian);

                latitudeString_drag = Cesium.Math.toDegrees(newCartographic.latitude);
                longitudeString_drag = Cesium.Math.toDegrees(newCartographic.longitude);
                var alt = Cesium.Math.toDegrees(newCartographic.height);
                // longitudeString_drag = newCartographic.longitude / Math.PI * 180
                // latitudeString_drag = newCartographic.latitude / Math.PI * 180
                // var alt = newCartographic.height / Math.PI * 180
                // var loc = scene.globe.ellipsoid.cartographicToCartesian(newCartographic)

                dragging_entity.position.setValue(newCartesian);
                for (var i = 0; i < MylabelsLineArr.length; i++) {
                    var bline = MylabelsLineArr[i]
                    if (dragging_entity.name == bline.line.name) {

                        bline.line.polyline.positions = Cesium.Cartesian3.fromDegreesArrayHeights([bline.orig_x, bline.orig_y, 0, longitudeString_drag, latitudeString_drag, 0])
                        MylabelsButtonArr[i].position.setValue(newCartesian)
                    }
                }

                // dragging_entity.handleMouseDown(movement)
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        handler.setInputAction(
            function() {
                //swap ship Shape at here!!!
                //currDistance  for 3D
                console.log('entering left_up')
                if (dragging) {
                    dragging = false;
                    //此处先获取拖动后，释放鼠标时当前经纬度  curr_lon    curr_lat

                    //  alert(dragging_entity.position._value.x)
                    scene.screenSpaceCameraController.enableRotate = true;
                }
                var vp = new Cesium.Viewport()
                    // var x_endmove = movement.position.x

                // var dragedlen = x_endmove - x_startmove
                var w0 = 0;
                var h0 = 0;
                var w1 = myviewer.scene.canvas.clientWidth;
                //  w1 += Math.abs(dragedlen);
                var h1 = myviewer.scene.canvas.clientHeight;
                var currscene = myviewer.scene
                    //   var movedRect = vp.getCurrCameraViewPortRealUg(w0, h0, w1, h1, currscene)
                var movedRect = null
                    // var gsh = new Cesium.g_ships(myviewer)
                    // var tsh = new Cesium.t_ships(myviewer)
                var msh = new Cesium.tmodel_ships(myviewer, myPolylinesCollection)

                var muycurrDistance = document.getElementsByClassName('distance-legend-label')[0].innerHTML
                if (muycurrDistance.indexOf('km' > 0)) {

                    var cameraPosition = myviewer.scene.camera.positionWC;
                    var ellipsoidPosition = myviewer.scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
                    var distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3()));
                    var tt = Number(distance)
                    if (tt >= 300000) {
                        return
                    }

                }

                if (myviewer.scene.camera._isTwoD) {

                    // var color = Cesium.Color.LIGHTSKYBLUE;
                    swap = 0

                } else {

                    // var color = Cesium.Color.LIGHTSKYBLUE;
                    var camera = myviewer.scene.camera;
                    var cameraPosition = camera.positionWC;
                    var ellipsoidPosition = myviewer.scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
                    var distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3()));
                    if (distance > swap_distance) {
                        return
                    }
                  //  document.getElementById('wl_lonlat_entity').innerHTML = '距离地面:' + distance;


                    // swapedAmt += msh.swaptoTriangleShip_leftup(polygon_billboards, color,
                    //         swaparr, CylinderShipArr, swapcount, movedRect, view_angle_rate_left)
                    //     //   this.swaptoPolygonShip(myviewer, color, swaparr, swapcount)
                    // document.getElementById("swap_amt").innerHTML = CylinderShipArr.length;
                    // swap = 0


                }

            }, Cesium.ScreenSpaceEventType.LEFT_UP);



        //show 2d


    };

    //热区 热力  热点
    // this.addHotZoon = function() {
    //     var instance = new Cesium.HeatmapImageryProvider({
    //             //88  118  24  40
    //             "radius": 200,
    //             "bounds": { 'north': 117.43582929, 'east': 40.13856899, 'south': 44.43606916, 'west': 118.13833844 },
    //             "data": {
    //                 'min': 0,
    //                 'max': 100,
    //                 'points': [{ "x": 110.1383442264, "y": 41.4360048372, "value": 769 },
    //                     { "x": 112.1384363011, "y": 42.4360298848, "value": 63 },
    //                     { "x": 113.138368102, "y": 43.4358360603, "value": 10 }
    //                 ]
    //             }
    //         })
    //         //var layer = myviewer.scene.globe.imageryLayers
    //     var clayer = myviewer.scene.globe.imageryLayers.addImageryProvider(instance)
    //     this.flytohereb(117.13833844, 40.43606916, 5000)
    // }
    this.addHotZoon = function() {
        var instance = new Cesium.HeatmapImageryProvider({
                //88  118  24  40
                "bounds": { 'north': -41.43582929, 'east': 147.13856899, 'south': -41.43606916, 'west': 147.13833844 },
                "data": {
                    'min': 0,
                    'max': 100,
                    'points': [{ "x": 147.1383442264, "y": -41.4360048372, "value": 76 },
                        { "x": 147.1384363011, "y": -41.4360298848, "value": 63 },
                        { "x": 147.138368102, "y": -41.4358360603, "value": 1 },
                        { "x": 147.1385627739, "y": -41.4358799123, "value": 21 },
                        { "x": 147.1385138501, "y": -41.4359327669, "value": 28 },
                        { "x": 147.1385031219, "y": -41.4359730105, "value": 41 },
                        { "x": 147.1384127393, "y": -41.435928255, "value": 75 },
                        { "x": 147.1384551136, "y": -41.4359450132, "value": 3 },
                        { "x": 147.1384927196, "y": -41.4359158649, "value": 45 }, { "x": 147.1384938639, "y": -41.4358498311, "value": 45 },
                        { "x": 147.1385183299, "y": -41.4360213794, "value": 93 }, { "x": 147.1384007925, "y": -41.4359860133, "value": 46 },
                        { "x": 147.1383604844, "y": -41.4358298672, "value": 54 }, { "x": 147.13851025, "y": -41.4359098303, "value": 39 },
                        { "x": 147.1383874733, "y": -41.4358511035, "value": 34 }, { "x": 147.1384981796, "y": -41.4359355403, "value": 81 },
                        { "x": 147.1384504107, "y": -41.4360332348, "value": 39 }, { "x": 147.1385582664, "y": -41.4359788335, "value": 20 },
                        { "x": 147.1383967364, "y": -41.4360581999, "value": 35 }, { "x": 147.1383839615, "y": -41.436016316, "value": 47 },
                        { "x": 147.1384082712, "y": -41.4358423338, "value": 36 }, { "x": 147.1385092651, "y": -41.4358577623, "value": 69 },
                        { "x": 147.138360356, "y": -41.436046789, "value": 90 }, { "x": 147.138471893, "y": -41.4359184292, "value": 88 },
                        { "x": 147.1385605689, "y": -41.4360271359, "value": 81 }, { "x": 147.1383585714, "y": -41.4359362476, "value": 32 },
                        { "x": 147.1384939114, "y": -41.4358844253, "value": 67 }, { "x": 147.138466724, "y": -41.436019121, "value": 17 },
                        { "x": 147.1385504355, "y": -41.4360614056, "value": 49 }, { "x": 147.1383883832, "y": -41.4358733544, "value": 82 },
                        { "x": 147.1385670669, "y": -41.4359650236, "value": 25 }, { "x": 147.1383416534, "y": -41.4359310876, "value": 82 }, { "x": 147.138525285, "y": -41.4359394661, "value": 66 }, { "x": 147.1385487719, "y": -41.4360137656, "value": 73 }, { "x": 147.1385496029, "y": -41.4359187277, "value": 73 }, { "x": 147.1383989222, "y": -41.4358556562, "value": 61 }, { "x": 147.1385499424, "y": -41.4359149305, "value": 67 }, { "x": 147.138404523, "y": -41.4359563326, "value": 90 }, { "x": 147.1383883675, "y": -41.4359794855, "value": 78 }, { "x": 147.1383967187, "y": -41.435891185, "value": 15 }, { "x": 147.1384610005, "y": -41.4359044797, "value": 15 }, { "x": 147.1384688489, "y": -41.4360396127, "value": 91 }, { "x": 147.1384431875, "y": -41.4360684409, "value": 8 }, { "x": 147.1385411067, "y": -41.4360645847, "value": 42 }, { "x": 147.1385237178, "y": -41.4358843181, "value": 31 }, { "x": 147.1384406464, "y": -41.4360003831, "value": 51 }, { "x": 147.1384679169, "y": -41.4359950456, "value": 96 }, { "x": 147.1384194314, "y": -41.4358419739, "value": 22 }, { "x": 147.1385049792, "y": -41.4359574813, "value": 44 }, { "x": 147.1384097378, "y": -41.4358598672, "value": 82 }, { "x": 147.1384993219, "y": -41.4360352975, "value": 84 }, { "x": 147.1383640499, "y": -41.4359839518, "value": 81 }
                    ]
                }
            })
            //var layer = myviewer.scene.globe.imageryLayers
        var clayer = myviewer.scene.globe.imageryLayers.addImageryProvider(instance)
        this.flytohereb(147.13833844, -41.43606916, 5000)
    }
    this.addHotZoonbk = function() {
        let bounds = {
            west: 147.13833844,
            east: 147.13856899,
            south: -42.43606916,
            north: -41.43582929
        };
        // init heatmap
        let heatMap = CesiumHeatmap.create(
            myviewer, // your cesium viewer
            bounds, // bounds for heatmap layer
            {
                // heatmap.js options go here
                //maxOpacity: 0.8
            }
        );
        // random example data
        let data = [{ "x": 147.1383442264, "y": -41.4360048372, "value": 76 },
            { "x": 147.1384363011, "y": -41.4360298848, "value": 63 },
            { "x": 147.138368102, "y": -41.4358360603, "value": 1 },
            { "x": 147.1385627739, "y": -41.4358799123, "value": 21 },
            { "x": 147.1385138501, "y": -41.4359327669, "value": 28 },
            { "x": 147.1385031219, "y": -41.4359730105, "value": 41 },
            { "x": 147.1384127393, "y": -41.435928255, "value": 75 },
            { "x": 147.1384551136, "y": -41.4359450132, "value": 3 },
            { "x": 147.1384927196, "y": -41.4359158649, "value": 45 }, { "x": 147.1384938639, "y": -41.4358498311, "value": 45 },
            { "x": 147.1385183299, "y": -41.4360213794, "value": 93 }, { "x": 147.1384007925, "y": -41.4359860133, "value": 46 },
            { "x": 147.1383604844, "y": -41.4358298672, "value": 54 }, { "x": 147.13851025, "y": -41.4359098303, "value": 39 },
            { "x": 147.1383874733, "y": -41.4358511035, "value": 34 }, { "x": 147.1384981796, "y": -41.4359355403, "value": 81 },
            { "x": 147.1384504107, "y": -41.4360332348, "value": 39 }, { "x": 147.1385582664, "y": -41.4359788335, "value": 20 },
            { "x": 147.1383967364, "y": -41.4360581999, "value": 35 }, { "x": 147.1383839615, "y": -41.436016316, "value": 47 },
            { "x": 147.1384082712, "y": -41.4358423338, "value": 36 }, { "x": 147.1385092651, "y": -41.4358577623, "value": 69 },
            { "x": 147.138360356, "y": -41.436046789, "value": 90 }, { "x": 147.138471893, "y": -41.4359184292, "value": 88 },
            { "x": 147.1385605689, "y": -41.4360271359, "value": 81 }, { "x": 147.1383585714, "y": -41.4359362476, "value": 32 },
            { "x": 147.1384939114, "y": -41.4358844253, "value": 67 }, { "x": 147.138466724, "y": -41.436019121, "value": 17 },
            { "x": 147.1385504355, "y": -41.4360614056, "value": 49 }, { "x": 147.1383883832, "y": -41.4358733544, "value": 82 },
            { "x": 147.1385670669, "y": -41.4359650236, "value": 25 }, { "x": 147.1383416534, "y": -41.4359310876, "value": 82 }, { "x": 147.138525285, "y": -41.4359394661, "value": 66 }, { "x": 147.1385487719, "y": -41.4360137656, "value": 73 }, { "x": 147.1385496029, "y": -41.4359187277, "value": 73 }, { "x": 147.1383989222, "y": -41.4358556562, "value": 61 }, { "x": 147.1385499424, "y": -41.4359149305, "value": 67 }, { "x": 147.138404523, "y": -41.4359563326, "value": 90 }, { "x": 147.1383883675, "y": -41.4359794855, "value": 78 }, { "x": 147.1383967187, "y": -41.435891185, "value": 15 }, { "x": 147.1384610005, "y": -41.4359044797, "value": 15 }, { "x": 147.1384688489, "y": -41.4360396127, "value": 91 }, { "x": 147.1384431875, "y": -41.4360684409, "value": 8 }, { "x": 147.1385411067, "y": -41.4360645847, "value": 42 }, { "x": 147.1385237178, "y": -41.4358843181, "value": 31 }, { "x": 147.1384406464, "y": -41.4360003831, "value": 51 }, { "x": 147.1384679169, "y": -41.4359950456, "value": 96 }, { "x": 147.1384194314, "y": -41.4358419739, "value": 22 }, { "x": 147.1385049792, "y": -41.4359574813, "value": 44 }, { "x": 147.1384097378, "y": -41.4358598672, "value": 82 }, { "x": 147.1384993219, "y": -41.4360352975, "value": 84 }, { "x": 147.1383640499, "y": -41.4359839518, "value": 81 }
        ];
        let valueMin = 0;
        let valueMax = 100;

        // add data to heatmap
        heatMap.setWGS84Data(valueMin, valueMax, data);
        this.flytohereb(147.13833844, -41.43606916, 5000)
    };
    //在viewerCesiumNavigationMinin.js处也有切换操作
    this.swaptoPolygonShip = function(diste, rect) {


        if (currdistance == diste) {
            return 0
        } else {
            currdistance = diste
        }
        // myviewer.scene.primitives.removeAll()
        // alert('entering swaptoPolygonShip')
        var color = Cesium.Color.LIGHTSKYBLUE;

        this.g_ships.swaptoPolygonShip(polygon_billboards, color, swaparr, swapcount, rect, view_angle_rate)
            //   this.swaptoPolygonShip(myviewer, color, swaparr, swapcount)

        swap = 0
        return 0
    };
    /**
     *  切换到多边形目标.
     *
     * @param
     *
     * @returns {Number[]} The array that was packed into
     */
    //在viewerCesiumNavigationMinin.js处也有切换操作
    var geodesicd = new Cesium.EllipsoidGeodesic();
    this.swaptoTriangleShip = function(diste, rect) {
        var distances = [
            1, 2, 3, 5,
            10, 20, 30, 50,
            100, 200, 300, 500,
            1000, 2000, 3000, 5000,
            10000, 20000, 30000, 50000,
            100000, 200000, 300000, 500000,
            1000000, 2000000, 3000000, 5000000,
            10000000, 20000000, 30000000, 50000000
        ];
        var width = myviewer.scene.canvas.clientWidth;
        var height = myviewer.scene.canvas.clientHeight;
        var left = myviewer.scene.camera.getPickRay(new Cesium.Cartesian2((width / 2) | 0, height - 1));
        var right = myviewer.scene.camera.getPickRay(new Cesium.Cartesian2(1 + (width / 2) | 0, height - 1));
        var leftPosition = myviewer.scene.globe.pick(left, myviewer.scene);
        var rightPosition = myviewer.scene.globe.pick(right, myviewer.scene);
        var leftCartographic = myviewer.scene.globe.ellipsoid.cartesianToCartographic(leftPosition);
        var rightCartographic = myviewer.scene.globe.ellipsoid.cartesianToCartographic(rightPosition);
        geodesicd.setEndPoints(leftCartographic, rightCartographic);
        var pixelDistance = geodesicd.surfaceDistance;
        var maxBarWidth = 100;
        var distance;
        for (var i = distances.length - 1; i >= 0; --i) {
            if (distances[i] / pixelDistance < maxBarWidth) {
                distance = distances[i];
            }
        }
        if (distance > swap_distance) {
            return
        }


        if (currdistance == diste) {
            return 0
        } else {
            currdistance = diste
        }
        // var tshb = new Cesium.t_ships(myviewer)
        //  this.t_ships = new Cesium.t_ships(myviewer)
        var color = Cesium.Color.LIGHTSKYBLUE;
        var camera = myviewer.scene.camera;
        var cameraPosition = camera.positionWC;
        var ellipsoidPosition = myviewer.scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
        var tdistance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3()));
        // if (tdistance > swap_distance) {
        //     return
        // }
        //document.getElementById('wl_lonlat_entity').innerHTML = '距离地面:' + tdistance;

        // var recobj = this.Viewport.getCurrScreenObjs(myviewer.scene)
        // this.t_ships.__proto__.swapToTriangleShip(polygon_billboards, color, swaparr, swapcount, rect, view_angle_rate)
        // this.tmodel_ships.swaptoTriangleShipb(polygon_billboards, color, swaparr, CylinderShipArr, swapcount, rect, view_angle_rate)
        //     //   keepsizeug.swaptoTriangleShipb(polygon_billboards, color, swaparr, swapcount, rect, view_angle_rate)
        // document.getElementById("swap_amt").innerHTML = CylinderShipArr.length;

        // swap = swapedAmt
        return swapedAmt
    };
    this.swaptoRoundShip = function(diste) {


        if (currRoundDistance == diste) {
            return
        } else {
            currRoundDistance = diste
        }
        try {


            //myPolylinesCollection
            myPolylinesCollection.removeAll()
            CylinderShipArr = this.g_ships.removeAllShapedShip(CylinderShipArr, swaparr, swapcount)
            CylinderShipArr = CylinderShipArr || []
                //    alert('delete' + CylinderShipArr.length)
                // polygon_billboards.removeAll()
                //  myviewer.scene.primitives.removeAll()
            var color = Cesium.Color.LIGHTSKYBLUE;
            var outlineColor = Cesium.Color.PURPLE;
            //  pointPrimitives = myviewer.scene.primitives.add(new Cesium.PointPrimitiveCollection());

            //  this.g_ships.swaptoRoundShip(pointPrimitives, color, outlineColor, swaparr, swapcount)
            //   for (var w = 1; w < 5; w++) {
            //       for (var t = total; t < 100000 + total; t++) {
            //           this.g_ships.swaptoRoundShip(pointPrimitives, color, outlineColor, swaparr, swapcount)
            //       }
            //       total += 100000
            //   }

            swapedAmt = 0
            document.getElementById("swap_amt").innerHTML = CylinderShipArr.length;
            // this.swaptoRoundShip(myviewer, color, outlineColor, swaparr, swapcount)

            swap = 1
            return 1
        } catch (exception) {}

    };





    this.showSatellitesPath = function() {
        //myviewer.dataSources.removeAll();
        satelliteLayer.load('../Apps/SampleData/simple.czml')
        myviewer.dataSources.add(satelliteLayer);

        myviewer.camera.flyHome(0);
    };
    this.delSatellitesPath = function() {
        myviewer.dataSources.remove(satelliteLayer)
    }
    this.changeAllLabel = function() {
        var colorHash = {};
        ////
        var allentities = myviewer.entities.values;

        for (var i = 0; i < allentities.length; i++) {
            var entity = allentities[i];
            var label;
            label = {
                text: entity._name,
                font: '4pt monospace',
                fillColor: Cesium.Color.WHITE,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 4,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                horizontalOrigin: Cesium.horizontalOrigin.RIGHT,
                pixelOffset: new Cesium.Cartesian2(0, -9)
            };
            entity.label = label;
        }
    };
    this.delAllLabel = function() {
        var allentities = myviewer.entities.values;
        for (var i = 0; i < allentities.length; i++) {
            var entity = allentities[i];
            entity.label = null;
        }

    };
    this.delplaneHistory = function() {
        myviewer.entities.remove(this.plane_entity)
        myviewer.entities.remove(entity_fire)
        myviewer.scene.primitives.remove(particleSystem)
        for (var i = 0; i < plane_position_list.length; i++) {
            myviewer.entities.remove(plane_position_list[i])
        }
        this.plane_history_num = 0
    };
    this.SetVedioSpeed = function(iTimeStep) {

        playback.set_realspeed(iTimeStep)
        playbackball.set_realspeed(iTimeStep)
    };
    this.settileset = function() {
        var tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
            url: 'https://beta.cesium.com/api/assets/1459?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzNjUyM2I5Yy01YmRhLTQ0MjktOGI0Zi02MDdmYzBjMmY0MjYiLCJpZCI6NDQsImFzc2V0cyI6WzE0NTldLCJpYXQiOjE0OTkyNjQ3ODF9.SW_rwY-ic0TwQBeiweXNqFyywoxnnUBtcVjeCmDGef4'
        }));

        tileset.readyPromise.then(function() {
            var boundingSphere = tileset.boundingSphere;
            viewer.camera.viewBoundingSphere(boundingSphere, new Cesium.HeadingPitchRange(0.5, -0.2, boundingSphere.radius * 4.0));
            viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
        }).otherwise(function(error) {
            throw (error);
        });


    };

    this.restart_shiphistory = function(shipid, ship_lon, ship_lat, ship_rotation) {
        this.del_shipHistory(shipid)

        // posArr_rail = []
        shallIstopShipHistory = false
        stopShipHistoryPoint = -1
            //restart
            // this.shiphistoryUgNoControlFindSpecifiedShip(shipid, ship_lon, ship_lat, ship_rotation)
        var currShip
        var currGltfUrl = 'ball'
            //此处应预处理多边形角度 muycurrDistance ,该方法适合处理球形目标轨迹数据

        for (var i = 0; i < swaparr.length; i++) {
            var name = swaparr[i].myball.name
            var id = swaparr[i].myball.id.split(';')[0]
            if (id == shipid || id.replace('roundobj', 'flexship') == shipid) {
                //考虑删除这条船！！！！或者更新为下面那条船
                currShip = swaparr[i].myball
                    //isPointInstall

                if (typeof(swaparr[i].ref) != "undefined") {
                    currShip = swaparr[i]
                    if (typeof(currShip.ref) != "undefined") {

                        //此处应预处理多边形角度 muycurrDistance ,该方法适合处理多边形形目标轨迹数据
                        currGltfUrl = currShip.ref.Cone.cacheKey.split('/')[7]
                            // playback.putOnBeginningPos(currGltfUrl, currShip.ref)
                        playback.deleteTimer()
                        currRailedShip = playback.shiphistoryUgNoControlV2(currShip.ref, ship_lon, ship_lat, ship_rotation)
                    } else {
                        currShip.position = posArr_rail[0].mypos
                            //设法获取currShip实体，然后传参数
                            //  this.shiphistoryUgNoControl(currShip, ship_lon, ship_lat, ship_rotation)
                    }

                } else {
                    currShip.position = posArr_rail[0].mypos
                        //  this.shiphistoryUgNoControl(currShip, ship_lon, ship_lat, ship_rotation)

                }

                break
            }
        }
    };
    this.del_shipHistory_stop = function(shipid) {
        playback.set_shallIstopShipHistory(true)
        playbackball.set_shallIstopShipHistory(true)
        for (var t = rail_nodes.length; t > 0; t--) {
            myviewer.entities.remove(rail_nodes[t])

            // console.log(pathPosition)
            // pathPosition._property._times.splice(t, 1)
            // pathPosition._property._values.splice(t, 1)
            pathPosition._property._times.pop()
            pathPosition._property._values.pop()
                //倒退位置
            stopShipHistoryPoint = t
        }
        pathPosition._property._times = []
        pathPosition._property._values = []
       // stopShipHistoryPoint = -1
        if (Cesium.defined(currRailedShip)) {
            myviewer.scene.primitives.remove(currRailedShip.ship);
            myviewer.scene.primitives.remove(currRailedShip.speedline);
        }
        // playback.setStopShipHistoryPoint(-1)
        // playbackball.setStopShipHistoryPoint(-1)
        // playback.set_shallIstopShipHistory(false)
        // playbackball.set_shallIstopShipHistory(false)

    };
    this.del_shipHistory = function(shipid) {
        playback.set_shallIstopShipHistory(true)
        playbackball.set_shallIstopShipHistory(true)
        for (var t = rail_nodes.length; t > 0; t--) {
            myviewer.entities.remove(rail_nodes[t])

            // console.log(pathPosition)
            // pathPosition._property._times.splice(t, 1)
            // pathPosition._property._values.splice(t, 1)
            pathPosition._property._times.pop()
            pathPosition._property._values.pop()
                //倒退位置
            stopShipHistoryPoint = t
        }
        pathPosition._property._times = []
        pathPosition._property._values = []
        stopShipHistoryPoint = -1
        if (Cesium.defined(currRailedShip)) {
            myviewer.scene.primitives.remove(currRailedShip.ship);
            myviewer.scene.primitives.remove(currRailedShip.speedline);
        }
        playback.setStopShipHistoryPoint(-1)
        playbackball.setStopShipHistoryPoint(-1)
        playback.set_shallIstopShipHistory(false)
        playbackball.set_shallIstopShipHistory(false)

    };

    //轨迹快进
    this.fastForword_shiphistory = function(shipid) {

        playback.fastForword_shiphistoryByHand(shipid)
        playbackball.fastForword_shiphistoryByHand(shipid)
    };
    this.emptyAllRail=function(shipid){
       // alert('entering shipid emptyAllRail:'+shipid)
       currRailedShip = playback.getCurrRailedShip()
       stopShipHistoryPoint = playback.getStopShipHistoryPoint()
        
        playbackball.removeAllRail(shipid)
        
    };
    //删除轨迹 倒退
    this.backdel_shiphistory = function(shipid) {
        //posArr_rail  stopShipHistoryPoint rail_nodes

        currRailedShip = playback.getCurrRailedShip()
            //playback.set_shallIstopShipHistory(true)
        stopShipHistoryPoint = playback.getStopShipHistoryPoint()
            //  playback.set_shall_I_back(true)
            // var backdel = new Cesium.BackDel(myviewer, pathPosition, posArr_rail, stopShipHistoryPoint, currRailedShip, rail_nodes)
            // backdel.backdel_shiphistory(shipid)
        playback.backdel_shiphistoryByHand(shipid)
        playbackball.backdel_shiphistoryByHand(shipid)
    };
    //暂停轨迹回放、

    this.temperaryStopShipHistory = function(currshipid) {

        shallIstopShipHistory = true
        playback.set_shallIstopShipHistory(true)
        playbackball.set_shallIstopShipHistory(true)
    };
    //继续播放轨迹回放
    this.continueShipHistory = function(currshipid) {
        debugger
        shallIstopShipHistory = true
        playback.set_shallIstopShipHistory(true)
        playbackball.set_shallIstopShipHistory(true)

        playback.set_shall_I_back(false)
    };


    //结束播放，并全部显示
    this.EndPlayHistoryTrack = function(shipid, ship_lon, ship_lat, ship_rotation, trackDotValue) {

        //  playbackball.EndPlayHistoryTrack(currshipid, ship_lon, ship_lat, ship_rotation, trackDotValue)
        this.del_shipHistory(shipid)

        // posArr_rail = []
        shallIstopShipHistory = true
        stopShipHistoryPoint = -1
            //restart
        var currShip
        var currGltfUrl = 'ball'
            //此处应预处理多边形角度 muycurrDistance ,该方法适合处理球形目标轨迹数据

        for (var i = 0; i < swaparr.length; i++) {
            var name = swaparr[i].myball.name
            var id = swaparr[i].myball.id.split(';')[0]
            if (id == shipid || id.replace('roundobj', 'flexship') == shipid) {
                //考虑删除这条船！！！！或者更新为下面那条船
                currShip = swaparr[i].myball
                    //isPointInstall

                if (typeof(swaparr[i].ref) != "undefined") {
                    currShip = swaparr[i]
                    if (typeof(currShip.ref) != "undefined") {

                        //此处应预处理多边形角度 muycurrDistance ,该方法适合处理多边形形目标轨迹数据
                        currGltfUrl = currShip.ref.Cone.cacheKey.split('/')[7]

                        // myapp.createRailData(ship_lon, ship_lat, currshipid, currGltfUrl, ship_rotation)
                        currRailedShip = playback.EndPlayHistoryTrack(currShip.ref, ship_lon, ship_lat, ship_rotation, trackDotValue)
                    } else {
                        currShip.position = posArr_rail[0].mypos
                            //设法获取currShip实体，然后传参数
                        playbackball.EndPlayHistoryTrack(currShip, ship_lon, ship_lat, ship_rotation, trackDotValue)
                    }

                } else {
                    currShip.position = posArr_rail[0].mypos
                    playbackball.EndPlayHistoryTrack(currShip, ship_lon, ship_lat, ship_rotation, trackDotValue)

                }

                break
            }
        }
    };
    //目标轨迹追踪
    // start from api_SingleshiphistoryUgNoControl
    var node_jump = 0
        //trackDotValue 轨迹总点数 开始播放
    this.shiphistoryUgNoControlFindSpecifiedShip = function(currshipid, ship_lon, ship_lat, ship_rotation, select_vediospeed, trackDotValue) {
        limited_rail = trackDotValue
            // var startlon = parseFloat(ship_lon) + Math.random() / 1000
            // var startlat = parseFloat(ship_lat) + Math.random() / 1000
            debugger
        var currShip
        var currGltfUrl = 'ball'
        posArr_rail = posArr_rail || []
        rail_nodes = rail_nodes || []
        pathPosition = new Cesium.SampledPositionProperty();
        //此处应预处理多边形角度 muycurrDistance ,该方法适合处理球形目标轨迹数据
        this.createRailData(ship_lon, ship_lat, currshipid, currGltfUrl, ship_rotation)
        for (var i = 0; i < swaparr.length; i++) {
            var name = swaparr[i].myball.name
            var id = swaparr[i].myball.id.split(';')[0]
            if (id == currshipid || id.replace('roundobj', 'flexship') == currshipid) {
                //考虑删除这条船！！！！或者更新为下面那条船
                currShip = swaparr[i].myball
                    //isPointInstall

                if (typeof(swaparr[i].ref) != "undefined") {
                    currShip = swaparr[i]
                    if (typeof(currShip.ref) != "undefined") {

                        //此处应预处理多边形角度 muycurrDistance ,该方法适合处理多边形形目标轨迹数据
                        currGltfUrl = currShip.ref.Cone.cacheKey.split('/')[7]
                        myapp.createRailData(ship_lon, ship_lat, currshipid, currGltfUrl, ship_rotation)
                        playback.set_realspeed(select_vediospeed)
                        currRailedShip = playback.shiphistoryUgNoControlV2(currShip.ref, ship_lon, ship_lat, ship_rotation)
                            //2维轨迹数组，记录多条船轨迹
                        replayRecordArr.add(currshipid, currShip, posArr_rail, stopShipHistoryPoint, pathPosition, rail_nodes, 'polygon')
                            //replayRecordArr.push
                    } else {

                        //设法获取currShip实体，然后传参数
                        playbackball.shiphistoryUgNoControl(currShip, ship_lon, ship_lat, ship_rotation)
                            //2维轨迹数组，记录多条船轨迹
                        replayRecordArr.add(currshipid, currShip, posArr_rail, stopShipHistoryPoint, pathPosition, rail_nodes, 'ball')
                    }

                } else {
                    playbackball.shiphistoryUgNoControl(currShip, ship_lon, ship_lat, ship_rotation)
                        //2维轨迹数组，记录多条船轨迹
                    replayRecordArr.add(currshipid, currShip, posArr_rail, stopShipHistoryPoint, pathPosition, rail_nodes, 'ball')
                }

                //replayRecordArr.add(currshipid,)

                break
            }
        }



    };
    this.fallowShipFindSpecifiedShip = function(currshipid, ship_lon, ship_lat, ship_rotation) {
        var currShip

        for (var i = 0; i < swaparr.length; i++) {
            var name = swaparr[i].myball.name
            var id = swaparr[i].myball.id.split(';')[0]
            if (id == currshipid || id.replace('roundobj', 'flexship') == currshipid) {
                //考虑删除这条船！！！！或者更新为下面那条船
                currShip = swaparr[i].myball
                if (typeof(swaparr[i].ref) != "undefined") {
                    currShip = swaparr[i]
                    if (typeof(currShip.ref) != "undefined") {
                        this.fallowShipNoControlV2(currShip.ref, ship_lon, ship_lat, ship_rotation)
                    } else
                        playbackball.shiphistoryUgNoControl(currShip, ship_lon, ship_lat, ship_rotation)
                } else
                    playbackball.shiphistoryUgNoControl(currShip, ship_lon, ship_lat, ship_rotation)

                break
            }
        }



    };
    //创建回放数据
    //轨迹回放

    this.createRailData = function(end_lon, end_lat, currshipid, currGltfUrl, ship_rotation) {

        var startlon = parseFloat(end_lon) + Math.random() / 1000
        var startlat = parseFloat(end_lat) + Math.random() / 1000
        var position = Cesium.Cartesian3.fromDegrees(startlon, startlat, 0.0);
        var endPosition = Cesium.Cartesian3.fromDegrees(end_lon, end_lat, 0.0);
        var r = 0
        var heading = Cesium.Math.toRadians(0);
        var heading_line = Cesium.Math.toRadians(0);

        var pitch = Cesium.Math.toRadians(180);
        var pitch_line = Cesium.Math.toRadians(180);
        var roll = Cesium.Math.toRadians(90);
        var hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        var hpr_line = new Cesium.HeadingPitchRoll(heading_line, pitch_line, roll);
        // var hpRoll = new Cesium.HeadingPitchRoll();
        //此处应预处理多边形角度 是否处理取决于 muycurrDistance
        // var muycurrDistance = document.getElementsByClassName('distance-legend-label')[0].innerHTML
        // if (muycurrDistance.indexOf('km' > 0)) {
        //     if (Number(muycurrDistance.replace('km', '')) <= 5) {
        //         //此处应预处理多边形角度
        //     }
        // } else if (muycurrDistance.indexOf('km' < 0) && muycurrDistance.indexOf('m' > 0)) {
        //     //此处应预处理多边形角度
        // }

        switch (currGltfUrl) {
            case 'triangleug.gltf':

                break;
            case 'polygon5ug.gltf':
                heading = Cesium.Math.toRadians(ship_rotation);

                pitch = Cesium.Math.toRadians(180);

                roll = Cesium.Math.toRadians(270);
                hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
                break;

            case 'polygon6ug.gltf':
                heading = Cesium.Math.toRadians(ship_rotation);
                pitch = Cesium.Math.toRadians(180);
                roll = Cesium.Math.toRadians(270);
                hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
                break;
        }

        //var speed = 100;

        //旋转的单位角度
        var deltaRadians = Cesium.Math.toRadians(360.0);
        var speedVector = new Cesium.Cartesian3();
        var j = 0
        var fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator('north', 'west');
        var myunix_z = { 'x': 0, 'y': 0, 'z': 1 }
        speedVector = Cesium.Cartesian3.multiplyByScalar(myunix_z, speed_rail / 10, speedVector);
        posArr_rail = posArr_rail || []
        for (var t = 0; t <= limited_rail; t++) {
            deltaRadians = Cesium.Math.toRadians(360.0 * Math.random());
            var breadscrumb = {
                //航向
                'deltaRadians': deltaRadians,
                //航速
                'speed': 10 * Math.random()
            }
            hpRoll.heading += breadscrumb.deltaRadians;
            if (hpRoll.heading > Cesium.Math.TWO_PI) {
                hpRoll.heading -= Cesium.Math.TWO_PI;
            }

            hpr_line.heading += breadscrumb.deltaRadians;
            if (hpr_line.heading > Cesium.Math.TWO_PI) {
                hpr_line.heading -= Cesium.Math.TWO_PI;
            }
            var hpr_line = new Cesium.HeadingPitchRoll(heading_line, pitch_line, roll);
            //此处求出速度矢量，可以调整速度，还能调整船头指向

            var myunix_z = { 'x': 0, 'y': 0, 'z': 1 }
                //Cesium.Cartesian3.UNIT_X
            speedVector = Cesium.Cartesian3.multiplyByScalar(myunix_z, speed_rail / 10, speedVector);
            var mymodelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform);
            var mymodelMatrix_line = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpr_line, Cesium.Ellipsoid.WGS84, fixedFrameTransform);
            position = Cesium.Matrix4.multiplyByPoint(mymodelMatrix, speedVector, position);
            //shipPrimitiveLine.modelMatrix = shipPrimitive.modelMatrix
            var mypos = { 'x': position.x, 'y': position.y, 'z': position.z }


            var n = dateFormat(new Date(), "dd/mm/yyyy HH:MM:ss");


            var raildata = { 'mypos': mypos, 'heading': hpRoll.heading, 'pitch': pitch, 'roll': roll, 'datetime': n }
            posArr_rail.push(raildata)
        }
        var lastraildata = { 'mypos': endPosition, 'heading': hpRoll.heading, 'pitch': pitch, 'roll': roll, 'datetime': n }
        posArr_rail.push(lastraildata)
        posArr_rail.push(lastraildata)
        playback.setposArr_rail(posArr_rail)
        playbackball.setposArr_rail(posArr_rail)

    };




    this.fallowShipNoControlV2 = function(ref, lon, lat, ship_rotation) {



        var shipPrimitiveNoControl
        this.viewer.trackedEntity = undefined;
        var camera = myviewer.camera;
        if (this.fallowShip_num >= 3) {

            camera.lookAt(fallow_plane_center, hpRange);
            //   myviewer.trackedEntity = plane_entity;
            return
        }
        this.fallowShip_num += 1
            //   myviewer.trackedEntity = plane_entity;

        var canvas = myviewer.canvas;
        canvas.setAttribute('tabindex', '0'); // needed to put focus on the canvas
        canvas.addEventListener('click', function() {
            canvas.focus();
        });
        canvas.focus();
        var scene = myviewer.scene;
        //目标原始位置！！！！！
        var position = Cesium.Cartesian3.fromDegrees(lon, lat, 0.0);

        fallow_entityPath = myviewer.entities.add({
            position: pathPosition,
            name: 'path',
            path: {
                show: true,
                leadTime: 0,
                trailTime: trailTime_length,
                resolution: 1,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.1,
                    color: Cesium.Color.YELLOW
                }),
                width: 1
            }

        });


        var r = 0
            //  var fallow_plane_center = new Cesium.Cartesian3();
            //  var hpRange = new Cesium.HeadingPitchRange();
        var heading = Cesium.Math.toRadians(0);
        var heading_line = Cesium.Math.toRadians(0);

        var pitch = Cesium.Math.toRadians(180);
        var pitch_line = Cesium.Math.toRadians(180);
        var roll = Cesium.Math.toRadians(90);
        var hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        var hpr_line = new Cesium.HeadingPitchRoll(heading_line, pitch_line, roll);
        // var hpRoll = new Cesium.HeadingPitchRoll();

        //var speed = 100;
        var speed = 100;
        //旋转的单位角度
        var deltaRadians = Cesium.Math.toRadians(360.0);
        var speedVector = new Cesium.Cartesian3();
        var fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator('north', 'west');







        //检查看看ref里面是否包含testobj!!!!!!
        shipPrimitiveNoControl = ref.Cone

        var currGltfUrl = shipPrimitiveNoControl._cacheKey.split('/')[7]
        var myurl
        var testobj
        switch (currGltfUrl) {
            case 'triangleug.gltf':
                myurl = '../Apps/SampleData/TriangleWithoutIndices/new/triangleug.gltf'
                testobj = Cesium.Model.fromGltf({
                    id: shipPrimitiveNoControl.id,
                    //  url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.glb',
                    //  url: myurl,
                    url: '../Apps/SampleData/TriangleWithoutIndices/new/triangleug.gltf',
                    //  url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.dae',
                    // url: '../Apps/SampleData/RNPTBOAT35.dae',
                    //   url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
                    scale: 1.0,
                    color: shipPrimitiveNoControl.color,
                    //将原始位置放入旋转矩阵
                    modelMatrix: shipPrimitiveNoControl.modelMatrix,
                    minimumPixelSize: 58 * 1
                        // maximumScale: 128 * 1
                })
                scene.primitives.remove(ref.Cone)
                break;
            case 'polygon5ug.gltf':
                scene.primitives.remove(ref.Cone)

                heading = Cesium.Math.toRadians(ship_rotation);
                pitch = Cesium.Math.toRadians(180);
                roll = Cesium.Math.toRadians(270);
                var hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
                var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform)

                myurl = '../Apps/SampleData/TriangleWithoutIndices/new/polygon5ug.gltf'
                testobj = Cesium.Model.fromGltf({
                    id: shipPrimitiveNoControl.id,
                    //  url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.glb',
                    //  url: myurl,
                    url: '../Apps/SampleData/TriangleWithoutIndices/new/polygon5ug.gltf',
                    // url: '../Apps/SampleData/TriangleWithoutIndices/new/polygon5ug.gltf',
                    //  url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.dae',
                    // url: '../Apps/SampleData/RNPTBOAT35.dae',
                    //   url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
                    scale: 1.0,
                    color: Cesium.Color.YELLOW,
                    //将原始位置放入旋转矩阵
                    modelMatrix: modelMatrix,
                    //modelMatrix: shipPrimitiveNoControl.modelMatrix,
                    minimumPixelSize: 58 * 1
                        // maximumScale: 128 * 1
                })

                break;
            case 'polygon6ug.gltf':

                scene.primitives.remove(ref.Cone)

                heading = Cesium.Math.toRadians(ship_rotation);
                pitch = Cesium.Math.toRadians(180);
                roll = Cesium.Math.toRadians(270);
                var hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
                var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform)

                myurl = '../Apps/SampleData/TriangleWithoutIndices/new/polygon6ug.gltf'
                testobj = Cesium.Model.fromGltf({
                    id: shipPrimitiveNoControl.id,
                    //  url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.glb',
                    //  url: myurl,
                    url: '../Apps/SampleData/TriangleWithoutIndices/new/polygon6ug.gltf',
                    //  url: '../Apps/SampleData/TriangleWithoutIndices/new/polygon6ug.gltf',
                    //  url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.dae',
                    // url: '../Apps/SampleData/RNPTBOAT35.dae',
                    //   url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
                    scale: 1.0,
                    color: shipPrimitiveNoControl.color,
                    //将原始位置放入旋转矩阵
                    modelMatrix: modelMatrix,
                    minimumPixelSize: 58 * 1
                        // maximumScale: 128 * 1
                })

                break;
        }


        shipPrimitiveNoControl = scene.primitives.add(testobj);
        var shipPrimitiveLine = ref.polyline
        var shipPrimitiveLine = myviewer.scene.primitives.add(shipPrimitiveLine);

        //求出旋转后的位置，然后视角跟踪
        shipPrimitiveNoControl.readyPromise.then(function(model) {
            // Play and loop all animations at half-speed
            model.activeAnimations.addAll({
                speedup: 0.5,
                loop: Cesium.ModelAnimationLoop.REPEAT
            });

            // Zoom to model
            r = 2.0 * Math.max(model.boundingSphere.radius, camera.frustum.near);
            controller.minimumZoomDistance = r * 100.5;
            //fallow_plane_center这是求出旋转后的位置
            Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, fallow_plane_center);
            //此处是俯视的角度
            var heading = Cesium.Math.toRadians(230.0);
            var pitch = Cesium.Math.toRadians(-20.0);
            hpRange.heading = heading;
            hpRange.pitch = pitch;
            hpRange.range = r * 50.0 * 1000;
            //求出旋转后的位置，然后视角跟踪
            // camera.lookAt(fallow_plane_center, hpRange);
        });
        myviewer.trackedEntity = shipPrimitiveNoControl;


        // myviewer.scene.preRender.addEventListener(function(scene, time) {
        var limit = 40000
        var j = 0
        var myunix_z = { 'x': 0, 'y': 0, 'z': 1 }
            //Cesium.Cartesian3.UNIT_X  speedVector speed 应该是节点间距 是位移
        speedVector = Cesium.Cartesian3.multiplyByScalar(myunix_z, speed / 10, speedVector);

        //下面是模拟创建轨迹集合
        var posArr
        var limited = 40000
        posArr = posArr || []
        for (var t = 0; t <= limited; t++) {


            deltaRadians = Cesium.Math.toRadians(360.0 * Math.random());
            var breadscrumb = {
                //航向
                'deltaRadians': deltaRadians,
                //航速
                'speed': 10 * Math.random()
            }

            // turn right
            hpRoll.heading += breadscrumb.deltaRadians;
            if (hpRoll.heading > Cesium.Math.TWO_PI) {
                hpRoll.heading -= Cesium.Math.TWO_PI;
            }

            hpr_line.heading += breadscrumb.deltaRadians;
            if (hpr_line.heading > Cesium.Math.TWO_PI) {
                hpr_line.heading -= Cesium.Math.TWO_PI;
            }

            var hpr_line = new Cesium.HeadingPitchRoll(heading_line, pitch_line, roll);
            //此处求出速度矢量，可以调整速度，还能调整船头指向

            var myunix_z = { 'x': 0, 'y': 0, 'z': 1 }
                //Cesium.Cartesian3.UNIT_X
            speedVector = Cesium.Cartesian3.multiplyByScalar(myunix_z, speed / 10, speedVector);
            //旋转+平移= 速度变化后的位置, position位置一旦变化，因modelMatrix是通过position求出来的，因此modelMatrix也立即跟着变
            //采用的是递归算法，十分巧妙
            var mymodelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform);
            var mymodelMatrix_line = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpr_line, Cesium.Ellipsoid.WGS84, fixedFrameTransform);
            position = Cesium.Matrix4.multiplyByPoint(mymodelMatrix, speedVector, position);
            //shipPrimitiveLine.modelMatrix = shipPrimitive.modelMatrix
            var mypos = { 'x': position.x, 'y': position.y, 'z': position.z }


            var n = dateFormat(new Date(), "dd/mm/yyyy HH:MM:ss");


            var raildata = { 'mypos': mypos, 'heading': hpRoll.heading, 'pitch': pitch, 'roll': roll, 'datetime': n }
            posArr.push(raildata)
        }
        var myHproll = new Cesium.HeadingPitchRoll(posArr[0].heading, posArr[0].pitch, posArr[0].roll);
        mymodelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(posArr[0].mypos, myHproll, Cesium.Ellipsoid.WGS84, fixedFrameTransform);
        position = posArr[0].mypos
        shipPrimitiveLine.modelMatrix = mymodelMatrix
        shipPrimitiveNoControl.modelMatrix = mymodelMatrix
        myviewer.scene.preRender.addEventListener(function() {
            j++
            if (j >= limited) {
                return
            }
            //此处求出速度矢量，可以调整速度，还能调整船头指向


            //旋转+平移= 速度变化后的位置, position位置一旦变化，因modelMatrix是通过position求出来的，因此modelMatrix也立即跟着变
            //采用的是递归算法，  speedVector speed 应该是节点间距 是位移
            //  position = Cesium.Matrix4.multiplyByPoint(shipPrimitive.modelMatrix, speedVector, position);


            // position = Cesium.Matrix4.multiplyByPoint(shipPrimitive.modelMatrix, speedVector, position);
            // shipPrimitiveLine.position = position
            if (node_jump == 35 * 10) {
                myHproll = new Cesium.HeadingPitchRoll(posArr[j].heading, posArr[j].pitch, posArr[j].roll);
                mymodelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(posArr[j].mypos, myHproll, Cesium.Ellipsoid.WGS84, fixedFrameTransform);
                position = posArr[j].mypos
                shipPrimitiveLine.modelMatrix = mymodelMatrix
                shipPrimitiveNoControl.modelMatrix = mymodelMatrix
                var res = myviewer.entities.add({
                    position: position,
                    point: {
                        pixelSize: 3,
                        color: Cesium.Color.TRANSPARENT,
                        outlineColor: Cesium.Color.YELLOW,
                        outlineWidth: 1
                    },



                });
                node_jump = 0
            } else {
                node_jump++
            }



            //下面2项不能不要，一个是画线， 一个是移动船
            pathPosition.addSample(Cesium.JulianDate.now(), position);
            Cesium.Transforms.headingPitchRollToFixedFrame(position, myHproll, Cesium.Ellipsoid.WGS84, fixedFrameTransform, shipPrimitiveNoControl.modelMatrix);

        });






    };

    this.shiphistoryUg = function(lon, lat) {
        var shipPrimitive

        this.viewer.trackedEntity = undefined;
        var camera = myviewer.camera;
        // if (this.fallowPlane_num >= 1) {

        //     camera.lookAt(fallow_plane_center, hpRange);
        //     //   myviewer.trackedEntity = plane_entity;
        //     return
        // }
        // this.fallowPlane_num += 1
        //   myviewer.trackedEntity = plane_entity;

        var canvas = myviewer.canvas;
        canvas.setAttribute('tabindex', '0'); // needed to put focus on the canvas
        canvas.addEventListener('click', function() {
            canvas.focus();
        });
        canvas.focus();
        var scene = myviewer.scene;
        //目标原始位置！！！！！
        var position = Cesium.Cartesian3.fromDegrees(lon, lat, 0.0);
        var pathPosition = new Cesium.SampledPositionProperty();
        fallow_entityPath = myviewer.entities.add({
            position: pathPosition,
            name: 'path',
            path: {
                show: true,
                leadTime: 0,
                trailTime: 60000,
                resolution: 1,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.1,
                    color: Cesium.Color.YELLOW
                }),
                width: 1
            }

        });


        var r = 0
            //  var fallow_plane_center = new Cesium.Cartesian3();
            //  var hpRange = new Cesium.HeadingPitchRange();
        var heading = Cesium.Math.toRadians(0);
        var heading_line = Cesium.Math.toRadians(0);

        var pitch = Cesium.Math.toRadians(180);
        var pitch_line = Cesium.Math.toRadians(180);
        var roll = Cesium.Math.toRadians(90);
        var hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        var hpr_line = new Cesium.HeadingPitchRoll(heading_line, pitch_line, roll);
        // var hpRoll = new Cesium.HeadingPitchRoll();

        //var speed = 100;
        var speed = 100;
        var deltaRadians = Cesium.Math.toRadians(3.0);

        var speedVector = new Cesium.Cartesian3();
        var fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator('north', 'west');

        shipPrimitive = scene.primitives.add(Cesium.Model.fromGltf({
            //  url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.glb',
            url: '../Apps/SampleData/TriangleWithoutIndices/new/triangleug.gltf',
            //  url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.dae',
            // url: '../Apps/SampleData/RNPTBOAT35.dae',
            //   url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
            color: Cesium.Color.RED,
            //将原始位置放入旋转矩阵
            modelMatrix: Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform),
            minimumPixelSize: 58 * 1
                // maximumScale: 128 * 1
        }));
        var shipPrimitiveLine = myviewer.scene.primitives.add(Cesium.Model.fromGltf({
            //  url: '../Apps/SampleData/models/2CylinderEngine/2CylinderEngine.dae',


            url: '../Apps/SampleData/TriangleWithoutIndices/new/cylinderug2.gltf',
            modelMatrix: Cesium.Transforms.headingPitchRollToFixedFrame(position, hpr_line, Cesium.Ellipsoid.WGS84, fixedFrameTransform),
            scale: 2, // double size
            color: Cesium.Color.RED,
            // maximumScale: 20000, // never larger than 20000 * model size (overrides minimumPixelSize)
            allowPicking: true, //   pickable
            //航速线长度在此处控制
            minimumPixelSize: 45 + 30 * 1
        }));

        //求出旋转后的位置，然后视角跟踪
        shipPrimitive.readyPromise.then(function(model) {
            // Play and loop all animations at half-speed
            model.activeAnimations.addAll({
                speedup: 0.5,
                loop: Cesium.ModelAnimationLoop.REPEAT
            });

            // Zoom to model
            r = 2.0 * Math.max(model.boundingSphere.radius, camera.frustum.near);
            controller.minimumZoomDistance = r * 100.5;
            //fallow_plane_center这是求出旋转后的位置
            Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, fallow_plane_center);
            //此处是俯视的角度
            var heading = Cesium.Math.toRadians(230.0);
            var pitch = Cesium.Math.toRadians(-20.0);
            hpRange.heading = heading;
            hpRange.pitch = pitch;
            hpRange.range = r * 50.0 * 1000;
            //求出旋转后的位置，然后视角跟踪
            camera.lookAt(fallow_plane_center, hpRange);
        });
        myviewer.trackedEntity = shipPrimitive;
        //加了一个监听
        document.addEventListener('keydown', function(e) {

            switch (e.keyCode) {
                case 40:
                    if (e.shiftKey) {
                        // speed down  调整速度
                        //   speed = Math.max(--speed, 1);
                        speed -= 10
                    } else {
                        // pitch down
                        hpRoll.pitch -= deltaRadians;
                        if (hpRoll.pitch < -Cesium.Math.TWO_PI) {
                            hpRoll.pitch += Cesium.Math.TWO_PI;
                        }
                        hpr_line.pitch -= deltaRadians;
                        if (hpr_line.pitch < -Cesium.Math.TWO_PI) {
                            hpr_line.pitch += Cesium.Math.TWO_PI;
                        }

                    }
                    break;
                case 38: //调整速度
                    if (e.shiftKey) {
                        // speed up
                        //   speed = Math.min(++speed, 100);
                        speed += 10
                    } else {
                        // pitch up
                        hpRoll.pitch += deltaRadians;
                        if (hpRoll.pitch > Cesium.Math.TWO_PI) {
                            hpRoll.pitch -= Cesium.Math.TWO_PI;
                        }
                        hpr_line.pitch += deltaRadians;
                        if (hpr_line.pitch > Cesium.Math.TWO_PI) {
                            hpr_line.pitch -= Cesium.Math.TWO_PI;
                        }


                    }
                    break;
                case 39:
                    if (e.shiftKey) {
                        // roll right
                        hpRoll.roll += deltaRadians;
                        if (hpRoll.roll > Cesium.Math.TWO_PI) {
                            hpRoll.roll -= Cesium.Math.TWO_PI;
                        }

                        hpr_line.roll += deltaRadians;
                        if (hpr_line.roll > Cesium.Math.TWO_PI) {
                            hpr_line.roll -= Cesium.Math.TWO_PI;
                        }


                    } else {
                        //alert('turn right')
                        // turn right
                        hpRoll.heading += deltaRadians;
                        if (hpRoll.heading > Cesium.Math.TWO_PI) {
                            hpRoll.heading -= Cesium.Math.TWO_PI;
                        }

                        hpr_line.heading += deltaRadians;
                        if (hpr_line.heading > Cesium.Math.TWO_PI) {
                            hpr_line.heading -= Cesium.Math.TWO_PI;
                        }


                    }
                    break;
                case 37:
                    if (e.shiftKey) {
                        // roll left until
                        hpRoll.roll -= deltaRadians;
                        if (hpRoll.roll < 0.0) {
                            hpRoll.roll += Cesium.Math.TWO_PI;
                        }
                        hpr_line.roll -= deltaRadians;
                        if (hpr_line.roll < 0.0) {
                            hpr_line.roll += Cesium.Math.TWO_PI;
                        }




                    } else {
                        // alert('turn left')
                        // turn left
                        hpRoll.heading -= deltaRadians;
                        if (hpRoll.heading < 0.0) {
                            hpRoll.heading += Cesium.Math.TWO_PI;
                        }
                        hpr_line.heading -= deltaRadians;
                        if (hpr_line.heading < 0.0) {
                            hpr_line.heading += Cesium.Math.TWO_PI;
                        }



                    }
                    break;
                default:
            }
        });
        var headingSpan = document.getElementById('heading');
        var pitchSpan = document.getElementById('pitch');
        var rollSpan = document.getElementById('roll');
        var speedSpan = document.getElementById('speed');


        var fromBehind = document.getElementById('fromBehind');
        //   myviewer.trackedEntity = plane_entity;

        //此处监听速度和方向变化，此处应该是死循环
        myviewer.scene.preRender.addEventListener(function(scene, time) {
            headingSpan.innerHTML = Cesium.Math.toDegrees(hpRoll.heading).toFixed(1);
            pitchSpan.innerHTML = Cesium.Math.toDegrees(hpRoll.pitch).toFixed(1);
            rollSpan.innerHTML = Cesium.Math.toDegrees(hpRoll.roll).toFixed(1);
            speedSpan.innerHTML = speed.toFixed(1);
            //此处求出速度矢量，可以调整速度，还能调整船头指向

            var myunix_z = { 'x': 0, 'y': 0, 'z': 1 }
                //Cesium.Cartesian3.UNIT_X
            speedVector = Cesium.Cartesian3.multiplyByScalar(myunix_z, speed / 10, speedVector);
            //旋转+平移= 速度变化后的位置, position位置一旦变化，因modelMatrix是通过position求出来的，因此modelMatrix也立即跟着变
            //采用的是递归算法，十分巧妙
            position = Cesium.Matrix4.multiplyByPoint(shipPrimitive.modelMatrix, speedVector, position);
            shipPrimitiveLine.modelMatrix = shipPrimitive.modelMatrix
                // shipPrimitiveLine.position = position
            if (node_jump == 35 * 10) {
                var res = myviewer.entities.add({
                    entitytype: 'point',
                    position: position,
                    point: {
                        pixelSize: 3,
                        color: Cesium.Color.TRANSPARENT,
                        outlineColor: Cesium.Color.YELLOW,
                        outlineWidth: 1
                    },



                });
                node_jump = 0
            } else {
                node_jump++
            }




            pathPosition.addSample(Cesium.JulianDate.now(), position);
            Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform, shipPrimitive.modelMatrix);
            // Cesium.Transforms.headingPitchRollToFixedFrame(position, hpr_line, Cesium.Ellipsoid.WGS84, fixedFrameTransform, shipPrimitive.modelMatrix);
            //锁定目标
            if (fromBehind.checked) {
                // Zoom to model
                // alert(fallow_plane_center.x + '--' + fallow_plane_center.y + '--' + fallow_plane_center.z)
                //求出飞机旋转平移后新的位置
                Cesium.Matrix4.multiplyByPoint(shipPrimitive.modelMatrix, shipPrimitive.boundingSphere.center, fallow_plane_center);
                //  alert(fallow_plane_center.x + '--' + fallow_plane_center.y + '--' + fallow_plane_center.z)
                //   hpRange.heading = hpRoll.heading;
                //   hpRange.pitch = hpRoll.pitch;
                //实时跟踪飞机的位置
                camera.lookAt(fallow_plane_center, hpRange);
                //   myviewer.trackedEntity = shipPrimitive;
            }
        });






    }

    //轨迹追踪
    this.showHistory = function() {
        ////   viewer.trackedEntity = entity;
        //Set bounds of our simulation time
        if (this.plane_history_num >= 1) {
            myviewer.zoomTo(myviewer.entities, new Cesium.HeadingPitchRange(Cesium.Math.toRadians(-90), Cesium.Math.toRadians(-15), 7500));
            myviewer.trackedEntity = this.plane_entity;
            return
        }
        this.plane_history_num += 1
        var start = Cesium.JulianDate.fromDate(new Date(2015, 2, 25, 16));
        var stop = Cesium.JulianDate.addSeconds(start, 360, new Cesium.JulianDate());
        //Make sure viewer is at the desired time.
        myviewer.clock.startTime = start.clone();
        myviewer.clock.stopTime = stop.clone();
        myviewer.clock.currentTime = start.clone();
        myviewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
        myviewer.clock.multiplier = 10;
        //Set timeline to simulation bounds
        myviewer.timeline.zoomTo(start, stop);

        //Generate a random circular pattern with varying heights.
        function computeCirclularFlight(lon, lat, radius) {
            plane_position_list = plane_position_list || []
            var property = new Cesium.SampledPositionProperty();
            for (var i = 0; i <= 360; i += 45) {
                var radians = Cesium.Math.toRadians(i);
                var time = Cesium.JulianDate.addSeconds(start, i, new Cesium.JulianDate());
                var position = Cesium.Cartesian3.fromDegrees(lon + (radius * 1.5 * Math.cos(radians)), lat + (radius * Math.sin(radians)), Cesium.Math.nextRandomNumber() * 500 + 1750);
                property.addSample(time, position);

                //Also create a point for each sample we generate.
                var res = myviewer.entities.add({
                    position: position,
                    point: {
                        pixelSize: 8,
                        color: Cesium.Color.TRANSPARENT,
                        outlineColor: Cesium.Color.YELLOW,
                        outlineWidth: 3
                    }
                });
                plane_position_list.push(res)
            }
            return property;
        }
        var emitterModelMatrix = new Cesium.Matrix4();
        var hpr = new Cesium.HeadingPitchRoll();
        var trs = new Cesium.TranslationRotationScale();
        var translation = new Cesium.Cartesian3();
        var rotation = new Cesium.Quaternion();

        function computeEmitterModelMatrix() {

            hpr = Cesium.HeadingPitchRoll.fromDegrees(viewModel.heading, viewModel.pitch, viewModel.roll, hpr);

            trs.translation = Cesium.Cartesian3.fromElements(viewModel.transX, viewModel.transY, viewModel.transZ, translation);
            trs.rotation = Cesium.Quaternion.fromHeadingPitchRoll(hpr, rotation);

            return Cesium.Matrix4.fromTranslationRotationScale(trs, emitterModelMatrix);
        }
        //Compute the entity position property.
        var plane_position = computeCirclularFlight(-112.110693, 36.0994841, 0.03);

        //Actually create the entity
        this.plane_entity = myviewer.entities.add({

            //Set the entity availability to the same interval as the simulation time.
            availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
                start: start,
                stop: stop
            })]),

            //Use our computed positions
            position: plane_position,

            //Automatically compute orientation based on position movement.
            orientation: new Cesium.VelocityOrientationProperty(plane_position),

            //Load the Cesium plane model to represent the entity
            model: {
                uri: '../Apps/SampleData/models/CesiumAir/Cesium_Air.glb',
                //uri: '../Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
                // uri: '../Apps/SampleData/models/CesiumAir/Cesium_Air.dae',
                minimumPixelSize: 64
            },

            //Show the path as a pink line sampled in 1 second increments.
            path: {
                resolution: 1,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.1,
                    color: Cesium.Color.YELLOW
                }),
                width: 10
            }
        });
        myviewer.zoomTo(myviewer.entities, new Cesium.HeadingPitchRange(Cesium.Math.toRadians(-90), Cesium.Math.toRadians(-15), 7500));
        myviewer.trackedEntity = this.plane_entity;

        particleSystem = myviewer.scene.primitives.add(new Cesium.ParticleSystem({
            image: './Apps/SampleData/fire.png',

            startColor: Cesium.Color.RED.withAlpha(0.7),
            endColor: Cesium.Color.YELLOW.withAlpha(0.3),

            startScale: viewModel.startScale,
            endScale: viewModel.endScale,

            minimumLife: viewModel.minimumLife,
            maximumLife: viewModel.maximumLife,

            minimumSpeed: viewModel.minimumSpeed,
            maximumSpeed: viewModel.maximumSpeed,

            minimumWidth: viewModel.particleSize,
            minimumHeight: viewModel.particleSize,

            maximumWidth: viewModel.particleSize,
            maximumHeight: viewModel.particleSize,

            // Particles per second.
            rate: viewModel.rate,

            bursts: [
                new Cesium.ParticleBurst({
                    time: 5.0,
                    minimum: 300,
                    maximum: 500
                }),
                new Cesium.ParticleBurst({
                    time: 10.0,
                    minimum: 50,
                    maximum: 100
                }),
                new Cesium.ParticleBurst({
                    time: 15.0,
                    minimum: 200,
                    maximum: 300
                })
            ],

            lifeTime: 16.0,

            emitter: new Cesium.CircleEmitter(0.5),

            emitterModelMatrix: computeEmitterModelMatrix(),

            forces: [applyGravity]
        }));

        var gravityScratch = new Cesium.Cartesian3();

        function applyGravity(p, dt) {
            // We need to compute a local up vector for each particle in geocentric space.
            var position = p.position;

            Cesium.Cartesian3.normalize(position, gravityScratch);
            Cesium.Cartesian3.multiplyByScalar(gravityScratch, viewModel.gravity * dt, gravityScratch);

            p.velocity = Cesium.Cartesian3.add(p.velocity, gravityScratch, p.velocity);
        }
        var entityPosition = new Cesium.Cartesian3();
        var entityOrientation = new Cesium.Quaternion();
        var rotationMatrix = new Cesium.Matrix3();
        var modelMatrix = new Cesium.Matrix4();

        function computeModelMatrix(entity, time) {
            var position = Cesium.Property.getValueOrUndefined(entity.position, time, entityPosition);
            if (!Cesium.defined(position)) {
                return undefined;
            }
            // entity.orientation = new Cesium.VelocityOrientationProperty(circularPosition);
            var orientation = Cesium.Property.getValueOrUndefined(entity.orientation, time, entityOrientation);
            if (!Cesium.defined(orientation)) {
                modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position, undefined, modelMatrix);
            } else {
                modelMatrix = Cesium.Matrix4.fromRotationTranslation(Cesium.Matrix3.fromQuaternion(orientation, rotationMatrix), position, modelMatrix);
            }
            return modelMatrix;
        }
        var circularPosition = computeCirclularFlight(-112.110693, 36.0994841, 0.03);
        var staticPosition = Cesium.Cartesian3.fromDegrees(-112.110693, 36.0994841, 0.03);

        entity_fire = myviewer.entities.add({

            //Set the entity availability to the same interval as the simulation time.
            availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
                start: start,
                stop: stop
            })]),


            //Load the Cesium plane model to represent the entity
            model: {
                uri: './Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
                minimumPixelSize: 64
            },
            path: {
                resolution: 1,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.1,
                    color: Cesium.Color.RED
                }),
                width: 10
            },
            position: circularPosition,
            orientation: new Cesium.VelocityOrientationProperty(circularPosition),
        });
        myviewer.scene.preRender.addEventListener(function(scene, time) {
            particleSystem.modelMatrix = computeModelMatrix(entity_fire, time);

            // Account for any changes to the emitter model matrix.
            particleSystem.emitterModelMatrix = computeEmitterModelMatrix();

            // Spin the emitter if enabled.
            if (viewModel.spin) {
                viewModel.heading += 1.0;
                viewModel.pitch += 1.0;
                viewModel.roll += 1.0;
            }
        });


        //   Cesium.knockout.getObservable(viewModel, 'rate').subscribe(
        //       function(newValue) {
        //           particleSystem.rate = parseFloat(newValue);
        //       }
        //   );

        Cesium.knockout.getObservable(viewModel, 'particleSize').subscribe(
            function(newValue) {
                var particleSize = parseFloat(newValue);
                particleSystem.minimumWidth = particleSize;
                particleSystem.maximumWidth = particleSize;
                particleSystem.minimumHeight = particleSize;
                particleSystem.maximumHeight = particleSize;
            }
        );
        Cesium.knockout.getObservable(viewModel, 'minimumLife').subscribe(
            function(newValue) {
                particleSystem.minimumLife = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'maximumLife').subscribe(
            function(newValue) {
                particleSystem.maximumLife = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'minimumSpeed').subscribe(
            function(newValue) {
                particleSystem.minimumSpeed = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'maximumSpeed').subscribe(
            function(newValue) {
                particleSystem.maximumSpeed = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'startScale').subscribe(
            function(newValue) {
                particleSystem.startScale = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'endScale').subscribe(
            function(newValue) {
                particleSystem.endScale = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'fly').subscribe(
            function(newValue) {
                if (newValue) {
                    entity.position = circularPosition;
                    //Automatically compute orientation based on position movement.
                    entity.orientation = new Cesium.VelocityOrientationProperty(circularPosition);
                } else {
                    entity.position = circularPosition;
                    entity.orientation = new Cesium.VelocityOrientationProperty(circularPosition);;
                }
            }
        );

        Sandcastle.addToggleButton('Spin', viewModel.spin, function(checked) {
            viewModel.spin = checked;
        });

        Sandcastle.addToggleButton('Fly', viewModel.fly, function(checked) {
            viewModel.fly = checked;
        });

        Sandcastle.addToggleButton('Show', viewModel.show, function(checked) {
            entity.show = checked;
            particleSystem.show = checked;
        });

        var options = [{
            text: 'Circle',
            onselect: function() {
                particleSystem.emitter = new Cesium.CircleEmitter(0.5);
            }
        }, {
            text: 'Cone',
            onselect: function() {
                particleSystem.emitter = new Cesium.ConeEmitter(Cesium.Math.toRadians(45.0));
            }
        }, {
            text: 'Box',
            onselect: function() {
                particleSystem.emitter = new Cesium.BoxEmitter(new Cesium.Cartesian3(10.0, 10.0, 10.0));
            }
        }, {
            text: 'Sphere',
            onselect: function() {
                particleSystem.emitter = new Cesium.SphereEmitter(5.0);
            }
        }];

        Sandcastle.addToolbarMenu(options);

        //Sandcastle_End
        Sandcastle.finishedLoading();

        particleSystem.emitter = new Cesium.ConeEmitter(Cesium.Math.toRadians(45.0));




    };
    this.delfallowPlaneFire = function() {
        // myviewer.entities.remove(this.plane_entity)
        myviewer.entities.remove(entity_fire)
        myviewer.scene.primitives.remove(particleSystem)
        for (var i = 0; i < plane_position_list.length; i++) {
            myviewer.entities.remove(plane_position_list[i])
        }
        this.plane_fire_num = 0

    }

    this.fallowPlaneFire = function() {
        ////   viewer.trackedEntity = entity;
        //Set bounds of our simulation time
        if (this.plane_fire_num >= 1) {
            myviewer.zoomTo(myviewer.entities, new Cesium.HeadingPitchRange(Cesium.Math.toRadians(-90), Cesium.Math.toRadians(-15), 7500));
            myviewer.trackedEntity = entity_fire;
            return
        }
        this.plane_fire_num += 1
        var start = Cesium.JulianDate.fromDate(new Date(2015, 2, 25, 16));
        var stop = Cesium.JulianDate.addSeconds(start, 360, new Cesium.JulianDate());
        //Make sure viewer is at the desired time.
        myviewer.clock.startTime = start.clone();
        myviewer.clock.stopTime = stop.clone();
        myviewer.clock.currentTime = start.clone();
        myviewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
        myviewer.clock.multiplier = 10;
        //Set timeline to simulation bounds
        myviewer.timeline.zoomTo(start, stop);

        //Generate a random circular pattern with varying heights.
        function computeCirclularFlight(lon, lat, radius) {
            plane_position_list = plane_position_list || []
            var property = new Cesium.SampledPositionProperty();
            for (var i = 0; i <= 360; i += 45) {
                var radians = Cesium.Math.toRadians(i);
                var time = Cesium.JulianDate.addSeconds(start, i, new Cesium.JulianDate());
                var position = Cesium.Cartesian3.fromDegrees(lon + (radius * 1.5 * Math.cos(radians)), lat + (radius * Math.sin(radians)), Cesium.Math.nextRandomNumber() * 500 + 1750);
                property.addSample(time, position);

                //Also create a point for each sample we generate.
                var res = myviewer.entities.add({
                    position: position,
                    point: {
                        pixelSize: 3,
                        color: Cesium.Color.TRANSPARENT,
                        outlineColor: Cesium.Color.RED,
                        outlineWidth: 1
                    }
                });
                plane_position_list.push(res)
            }

            return property;
        }
        var emitterModelMatrix = new Cesium.Matrix4();
        var hpr = new Cesium.HeadingPitchRoll();
        var trs = new Cesium.TranslationRotationScale();
        var translation = new Cesium.Cartesian3();
        var rotation = new Cesium.Quaternion();

        function computeEmitterModelMatrix() {
            hpr = Cesium.HeadingPitchRoll.fromDegrees(viewModel.heading, viewModel.pitch, viewModel.roll, hpr);

            trs.translation = Cesium.Cartesian3.fromElements(viewModel.transX, viewModel.transY, viewModel.transZ, translation);
            trs.rotation = Cesium.Quaternion.fromHeadingPitchRoll(hpr, rotation);

            return Cesium.Matrix4.fromTranslationRotationScale(trs, emitterModelMatrix);
        }
        //Compute the entity position property.
        var plane_position = computeCirclularFlight(-112.110693, 36.0994841, 0.03);

        //Actually create the entity

        myviewer.zoomTo(myviewer.entities, new Cesium.HeadingPitchRange(Cesium.Math.toRadians(-90), Cesium.Math.toRadians(-15), 7500));
        //

        particleSystem = myviewer.scene.primitives.add(new Cesium.ParticleSystem({
            image: './Apps/SampleData/fire.png',

            startColor: Cesium.Color.RED.withAlpha(0.7),
            endColor: Cesium.Color.YELLOW.withAlpha(0.3),

            startScale: viewModel.startScale,
            endScale: viewModel.endScale,

            minimumLife: viewModel.minimumLife,
            maximumLife: viewModel.maximumLife,

            minimumSpeed: viewModel.minimumSpeed,
            maximumSpeed: viewModel.maximumSpeed,

            minimumWidth: viewModel.particleSize,
            minimumHeight: viewModel.particleSize,

            maximumWidth: viewModel.particleSize,
            maximumHeight: viewModel.particleSize,

            // Particles per second.
            rate: viewModel.rate,

            bursts: [
                new Cesium.ParticleBurst({
                    time: 5.0,
                    minimum: 300,
                    maximum: 500
                }),
                new Cesium.ParticleBurst({
                    time: 10.0,
                    minimum: 50,
                    maximum: 100
                }),
                new Cesium.ParticleBurst({
                    time: 15.0,
                    minimum: 200,
                    maximum: 300
                })
            ],

            lifeTime: 16.0,

            emitter: new Cesium.CircleEmitter(0.5),

            emitterModelMatrix: computeEmitterModelMatrix(),

            forces: [applyGravity]
        }));

        var gravityScratch = new Cesium.Cartesian3();

        function applyGravity(p, dt) {
            // We need to compute a local up vector for each particle in geocentric space.
            var position = p.position;

            Cesium.Cartesian3.normalize(position, gravityScratch);
            Cesium.Cartesian3.multiplyByScalar(gravityScratch, viewModel.gravity * dt, gravityScratch);

            p.velocity = Cesium.Cartesian3.add(p.velocity, gravityScratch, p.velocity);
        }
        var entityPosition = new Cesium.Cartesian3();
        var entityOrientation = new Cesium.Quaternion();
        var rotationMatrix = new Cesium.Matrix3();
        var modelMatrix = new Cesium.Matrix4();

        function computeModelMatrix(entity, time) {
            var position = Cesium.Property.getValueOrUndefined(entity.position, time, entityPosition);
            if (!Cesium.defined(position)) {
                return undefined;
            }
            // entity.orientation = new Cesium.VelocityOrientationProperty(circularPosition);
            var orientation = Cesium.Property.getValueOrUndefined(entity.orientation, time, entityOrientation);
            if (!Cesium.defined(orientation)) {
                modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position, undefined, modelMatrix);
            } else {
                modelMatrix = Cesium.Matrix4.fromRotationTranslation(Cesium.Matrix3.fromQuaternion(orientation, rotationMatrix), position, modelMatrix);
            }
            return modelMatrix;
        }
        var circularPosition = computeCirclularFlight(-112.110693, 36.0994841, 0.03);
        var staticPosition = Cesium.Cartesian3.fromDegrees(-112.110693, 36.0994841, 0.03);

        entity_fire = myviewer.entities.add({
            entitytype: 'fire',
            //Set the entity availability to the same interval as the simulation time.
            availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
                start: start,
                stop: stop
            })]),


            //Load the Cesium plane model to represent the entity
            model: {
                uri: './Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
                minimumPixelSize: 64
            },
            path: {
                resolution: 1,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.1,
                    color: Cesium.Color.RED
                }),
                width: 10
            },
            position: circularPosition,
            orientation: new Cesium.VelocityOrientationProperty(circularPosition),
        });
        myviewer.trackedEntity = entity_fire;
        myviewer.scene.preRender.addEventListener(function(scene, time) {
            particleSystem.modelMatrix = computeModelMatrix(entity_fire, time);

            // Account for any changes to the emitter model matrix.
            particleSystem.emitterModelMatrix = computeEmitterModelMatrix();

            // Spin the emitter if enabled.
            if (viewModel.spin) {
                viewModel.heading += 1.0;
                viewModel.pitch += 1.0;
                viewModel.roll += 1.0;
            }
        });


        //   Cesium.knockout.getObservable(viewModel, 'rate').subscribe(
        //       function(newValue) {
        //           particleSystem.rate = parseFloat(newValue);
        //       }
        //   );

        Cesium.knockout.getObservable(viewModel, 'particleSize').subscribe(
            function(newValue) {
                var particleSize = parseFloat(newValue);
                particleSystem.minimumWidth = particleSize;
                particleSystem.maximumWidth = particleSize;
                particleSystem.minimumHeight = particleSize;
                particleSystem.maximumHeight = particleSize;
            }
        );
        Cesium.knockout.getObservable(viewModel, 'minimumLife').subscribe(
            function(newValue) {
                particleSystem.minimumLife = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'maximumLife').subscribe(
            function(newValue) {
                particleSystem.maximumLife = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'minimumSpeed').subscribe(
            function(newValue) {
                particleSystem.minimumSpeed = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'maximumSpeed').subscribe(
            function(newValue) {
                particleSystem.maximumSpeed = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'startScale').subscribe(
            function(newValue) {
                particleSystem.startScale = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'endScale').subscribe(
            function(newValue) {
                particleSystem.endScale = parseFloat(newValue);
            }
        );

        Cesium.knockout.getObservable(viewModel, 'fly').subscribe(
            function(newValue) {
                if (newValue) {
                    entity.position = circularPosition;
                    //Automatically compute orientation based on position movement.
                    entity.orientation = new Cesium.VelocityOrientationProperty(circularPosition);
                } else {
                    entity.position = circularPosition;
                    entity.orientation = new Cesium.VelocityOrientationProperty(circularPosition);;
                }
            }
        );

        Sandcastle.addToggleButton('Spin', viewModel.spin, function(checked) {
            viewModel.spin = checked;
        });

        Sandcastle.addToggleButton('Fly', viewModel.fly, function(checked) {
            viewModel.fly = checked;
        });

        Sandcastle.addToggleButton('Show', viewModel.show, function(checked) {
            entity.show = checked;
            particleSystem.show = checked;
        });

        var options = [{
            text: 'Circle',
            onselect: function() {
                particleSystem.emitter = new Cesium.CircleEmitter(0.5);
            }
        }, {
            text: 'Cone',
            onselect: function() {
                particleSystem.emitter = new Cesium.ConeEmitter(Cesium.Math.toRadians(45.0));
            }
        }, {
            text: 'Box',
            onselect: function() {
                particleSystem.emitter = new Cesium.BoxEmitter(new Cesium.Cartesian3(10.0, 10.0, 10.0));
            }
        }, {
            text: 'Sphere',
            onselect: function() {
                particleSystem.emitter = new Cesium.SphereEmitter(5.0);
            }
        }];

        Sandcastle.addToolbarMenu(options);

        //Sandcastle_End
        Sandcastle.finishedLoading();

        particleSystem.emitter = new Cesium.ConeEmitter(Cesium.Math.toRadians(45.0));




    };
    this.addLabel = function() {
        var labels = myviewer.scene.primitives.add(new Cesium.LabelCollection());
        labels.add({
            id: 'label1 label',
            name: 'Another',
            position: Cesium.Cartesian3.fromDegrees(-75.1641667, 29.9522222),
            text: '一个标签',
            pixelOffset: new Cesium.Cartesian2(100, -100)
        });

    };
    this.addbillboardsUg = function() {
        // Demo settings
        var numberOfAircraft = 12;
        var centerLon = -90;
        var centerLat = 10;
        // Set bounds of our simulation time
        var start = Cesium.JulianDate.fromDate(new Date(2018, 2, 25, 16));
        var mid = Cesium.JulianDate.addSeconds(start, 4320, new Cesium.JulianDate());
        var stop = Cesium.JulianDate.addSeconds(start, 8640, new Cesium.JulianDate());
        // Make sure viewer is at the desired time.
        myviewer.clock.startTime = start.clone();
        myviewer.clock.stopTime = stop.clone();
        myviewer.clock.currentTime = mid.clone();
        myviewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
        myviewer.clock.multiplier = 10;
        myviewer.clock.shouldAnimate = false;
        myviewer.timeline.zoomTo(start, stop);


        function computeFlight(lon, lat, heading, color) {
            //  var position = Cesium.Cartesian3.fromDegrees(-75.59777 * Math.random(), 40.03883 * Math.random(), 0);
            var position = new Cesium.SampledPositionProperty();
            var startDegreesDistance = 1;
            var stopDegreesDistance = 5;
            var lon1 = lon + (-startDegreesDistance * Math.sin(Cesium.Math.toRadians(heading)));
            var lat1 = lat + (startDegreesDistance * Math.cos(Cesium.Math.toRadians(heading)));
            var lon2 = lon + (-stopDegreesDistance * Math.sin(Cesium.Math.toRadians(heading)));
            var lat2 = lat + (stopDegreesDistance * Math.cos(Cesium.Math.toRadians(heading)));
            var startPos = Cesium.Cartesian3.fromDegrees(lon1, lat1);
            var stopPos = Cesium.Cartesian3.fromDegrees(lon2, lat2);
            position.addSample(start, startPos);
            position.addSample(stop, stopPos);

            // Also create start/stop points.


            // Create an aircraft.
            var entity = myviewer.entities.add({
                availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
                    start: start,
                    stop: stop
                })]),
                position: position,

                // Automatically compute orientation based on position movement.
                // Only needed for 3D models.
                //orientation : new Cesium.VelocityOrientationProperty(position),

                billboard: {
                    image: '../Apps/Images/triangle.png',
                    width: 10, // default: undefined
                    height: 20, // default: undefined
                    //  image: '',
                    color: color,
                    alignedAxis: new Cesium.VelocityVectorProperty(position)
                },

                //   path: {
                //       material: new Cesium.PolylineGlowMaterialProperty({
                //           glowPower: 0.1,
                //           color: color.withAlpha(0.7)
                //       }),
                //       width: 0
                //   }
            });
        }

        // Create a radial array of aircraft.
        for (var i = 0; i < numberOfAircraft; ++i) {
            var color = (i > 0) ? Cesium.Color.YELLOW : Cesium.Color.ORANGERED;
            if (i === (numberOfAircraft * 0.5)) {
                color = Cesium.Color.WHITE;
            }
            computeFlight(centerLon, centerLat, i * 360 / numberOfAircraft, color);
        }

    }




    this.dropScaledShip = function() {
        var primitives = myviewer.scene.primitives;
        var ellipsoid = myviewer.scene.globe.ellipsoid;

        var billboards = new Cesium.BillboardCollection();
        var image = new Image();
        image.onload = function() {
            var textureAtlas = myviewer.scene.createTextureAtlas({ image: image });
            billboards.textureAtlas = textureAtlas;
            primitives.add(billboards);
        };
        image.src = '../images/test.gif';

        function addBillboard(tempLat, tempLon) {
            billboards.add({
                position: ellipsoid.cartographicToCartesian(Cesium.Cartographic.fromDegrees(tempLat, tempLon)),
                imageIndex: 0
            });
        }

        var tempLat = 0;
        var tempLon = 0;
        for (var i = 0; i < 1500; i++) {
            tempLat += 1;
            tempLon += 1;
            if (tempLat > 90) {
                tempLat = 0;
                tempLon = 0;
            }
            addBillboard(tempLat, tempLon);
        }
    }
    this.addSelfDefinedGeometry = function() {
        var result = new Cesium.Cartesian4()

        var m1 = Cesium.Matrix4.multiplyByTranslation(
            Cesium.Transforms.eastNorthUpToFixedFrame(myviewer.scene.globe.ellipsoid.cartographicToCartesian(
                Cesium.Cartographic.fromDegrees(-100.0, 40.0))),
            new Cesium.Cartesian3(0.0, 0.0, 200000.0), result);
        var modelMatrix = Cesium.Matrix4.multiplyByUniformScale(
            m1, new Cesium.Cartesian3(0.0, 0.0, 200000.0), result
        );
        var instance = new Cesium.GeometryInstance({
            geometry: new Cesium.GeometryPipeline.toWireframe(new Cesium.TetrahedronGeometry()),
            modelMatrix: modelMatrix,
            attributes: {
                color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.WHITE)
            }
        });
        //   var instance = new Cesium.GeometryInstance({
        //       geometry: new Cesium.TetrahedronGeometry(),
        //       modelMatrix: modelMatrix,
        //       attributes: {
        //           color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.WHITE)
        //       }
        //   });
        myviewer.scene.primitives.add(new Cesium.Primitive({
            geometryInstances: instance,
            appearance: new Cesium.PerInstanceColorAppearance({
                flat: true,
                translucent: false
            })
        }));
        //   myviewer.scene.primitives.add(Cesium.createTangentSpaceDebugPrimitive({
        //       geometryInstances: instance,
        //       modelMatrix: modelMatrix,
        //       length: 0.2
        //   }));
    }

    //   //  myviewer.scene.primitives.add(polyline);

    this.addFishArea = function() {

        if (fisharea != null) {
            return
        }

        var instances = [];

        for (var lon = -180.0; lon < 180.0; lon += 5.0) {
            for (var lat = -85.0; lat < 85.0; lat += 5.0) {
                instances.push(new Cesium.GeometryInstance({
                    geometry: new Cesium.RectangleGeometry({
                        rectangle: Cesium.Rectangle.fromDegrees(lon, lat, lon + 5.0, lat + 5.0),
                        vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
                    }),
                    attributes: {
                        color: new Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromRandom({ alpha: 0.5 }))
                    }
                }));
            }
        }

        fisharea = myviewer.scene.primitives.add(new Cesium.Primitive({
            geometryInstances: instances,
            appearance: new Cesium.PerInstanceColorAppearance()
        }));
    }

    this.removeFishArea = function() {
        myviewer.scene.primitives.remove(fisharea)
        fisharea = null
    }
    var currShipCount = 0
    var shipcount = 1000
    var constAddAmt = 50000






    this.changePolygonShipLocation = function() {

        this.viewer.entities = this.keepsize.changeLocation(this.viewer.entities, this.viewer.scene.globe.ellipsoid, currsize)
            // currsize++
    };
    this.RotatePolygonShip = function() {
        //   var ks = new Cesium.Keepsize()
        var degree = 90
        this.keepsize.RotateEntityShip(keepsizedShipArr.length, this.viewer, keepsizedShipArr, degree)

    };
    this.flytohereb = function(x, y, height) {
        //  Sandcastle.declare(flyInACity);

        var camera = myviewer.scene.camera;
        var initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(7.1077496389876024807, -31.987223091598949054, 0.025883251314954971306);

        camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(x, y, height),
            //   complete: function() {
            //       setTimeout(function() {
            //           camera.flyTo({
            //               destination: Cesium.Cartesian3.fromDegrees(x, y, 182000.0),
            //               orientation: {
            //                   //   heading: Cesium.Math.toRadians(200.0),
            //                   //   pitch: Cesium.Math.toRadians(-50.0)
            //                   heading: initialOrientation.heading,
            //                   pitch: initialOrientation.pitch,
            //                   roll: initialOrientation.roll
            //               },
            //               easingFunction: Cesium.EasingFunction.LINEAR_NONE
            //           });
            //           var cameraPosition = camera.positionWC;
            //           var ellipsoidPosition = myviewer.scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
            //           var distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3()));
            //           // alert(distance)
            //           init_distance = distance
            //           document.getElementById('wl_lonlat_entity').innerHTML = '距离地面:' + distance;
            //       }, 1000);
            //   }  105   33
            complete: function() {
                var cameraPosition = camera.positionWC;
                var ellipsoidPosition = myviewer.scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
                var distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3()));
                // alert(distance)
                init_distance = distance
              //  document.getElementById('wl_lonlat_entity').innerHTML = '距离地面:' + distance;
            }
        });
        var cameraPosition = camera.positionWC;
        var ellipsoidPosition = myviewer.scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
        var distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3()));
        // alert(distance)
        init_distance = distance
       // document.getElementById('wl_lonlat_entity').innerHTML = '距离地面:' + distance;
    }

    this.AddCylinderShips = function() {
        var ellipsoid = myviewer.scene.globe.ellipsoid;
        var onship = keepsizeug.InstallCylinderShip(myviewer, CylinderShipArr, currcylindershipsize, ellipsoid)
        document.getElementById("Triangleship_amt").innerHTML = CylinderShipArr.length;
        first_qship = onship
        this.flytohereb(onship.x, onship.y, 50000.0)
            //
            //   var test = Cesium.PrimitivePipeline.getCurrPosition()
            //   alert(test)
    };
    this.adjustSpeedLine = function() {
        //  keepsizeug.adjustSpeedLine()

    };
    var n_rotation_z = Math.round(Math.random() * 360, 0)
    n_rotation_z = 30
    var tss = 0
        //旋转模型2
    this.ChangeCylinderShipDegree = function() {

        var rotation_x = Math.round(Math.random() * 360, 1)

        var rotation_y = 180

        var n_rotation_z = 0
        var ellipsoid = myviewer.scene.globe.ellipsoid;
        // keepsizeug.rotateUg(rotation_x, rotation_y, n_rotation_z, ellipsoid,
        //     CylinderShipArr)
        keepsizeModel.rotateUg(rotation_x, rotation_y, n_rotation_z, ellipsoid,
                CylinderShipArr)
            // n_rotation_z = keepsizeug.RotateCylinderShip(rotation_x, rotation_y, n_rotation_z, ellipsoid)
            // n_rotation_z = keepsizeug.RotateCylinderShipQ(CylinderShipArr, rotation_x, rotation_y, n_rotation_z, ellipsoid)
            //  n_rotation_z = keepsizeug.RotateCylinderShipQUg(CylinderShipArr, rotation_x, rotation_y, n_rotation_z, ellipsoid)
            //   var test = Cesium.PrimitivePipeline.getCurrPosition()
            //   alert(test)

        // n_rotation_z = Number(Math.round(Math.random() * 90, 0))

        // n_rotation_z = Math.round(Math.random() * 360, 1)

    };



    //Camera.prototype.zoomIn = function(amount)

    this.addDatasource = function() {
        var czml = [{
            "id": "document",
            "name": "CZML Polygon - Intervals and Availability",
            "version": "1.0"

        }, {
            "id": "dynamicPolygon",
            "name": "Dynamic Polygon with Intervals",

            "polygon": {
                "positions": [{

                    "cartographicDegrees": [55, 50, 0, 55, 10, 0, -45, 30, 0]
                }],
                "material": {
                    "solidColor": {
                        "color": [{
                            "rgbaf": [1, 0, 1, 1]
                        }]
                    }
                }
            }
        }, {
            "id": "california",
            "name": "static california with set availability",

            "polygon": {
                "positions": {
                    "cartographicDegrees": [-120, 42, 50000, -124, 42, 30500, -124.5, 40, 3000, -123, 38, 0, -122, 36, 0, -120.8, 34.2, 0, -118, 34, 0, -117, 32.2, 6000, -115.5, 32.5, 1530, -115, 35, 1530, -120, 39, 30500]
                },
                "material": {
                    "solidColor": {
                        "color": {
                            "rgba": [255, 0, 0, 150]
                        }
                    }
                },
                "perPositionHeight": true,
                "extrudedHeight": 0
            }
        }, {
            "id": "pennsylvania",
            "name": "static pennsylvania with set availability",

            "polygon": {
                "positions": {
                    "cartographicDegrees": [-75.5, 42, 0, -79.8, 42, 0, -79.9, 42.3, 0, -80.5, 42, 0, -80.5, 39.8, 0, -75.7, 39.8, 0, -74.5, 40.2, 0, -75.2, 40.8, 0, -74.7, 41.3, 0]
                },
                "material": {
                    "solidColor": {
                        "color": {
                            "rgba": [0, 255, 0, 150]
                        }
                    }
                },
                "height": 50000,
                "extrudedHeight": 200000
            }
        }];

        var dataSource = new Cesium.CzmlDataSource();
        dataSource.load(czml);
        this.viewer.dataSources.add(dataSource);
        this.viewer.zoomTo(dataSource);
    };
    this.addstars = function() {

        var starcount = 100
        var e = 1800;

        //
        // var offset = new Cesium.Cartesian3(0, 90, 90);
        // var enuTransform = Cesium.Transforms.eastNorthUpToFixedFrame(position);
        // Cesium.Matrix4.multiplyByPointAsVector(enuTransform, offset, offset);

        // //Add the offset to the original position to get the final value.
        // Cesium.Cartesian3.add(position, offset, position);


        for (var i = 0; i < starcount; i++) {
            var mypos = Cesium.Cartesian3.fromDegrees(

                2 * e * Math.random(),
                2 * e * Math.random(),
                3000000 * Math.random()

            )
            var heading = Cesium.Math.toRadians(0.0);
            var pitch = Cesium.Math.toRadians(0.0);
            var roll = Cesium.Math.toRadians(90.0 * Math.random());
            var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
            var orientation = Cesium.Transforms.headingPitchRollQuaternion(mypos, hpr);
            var redCone = this.viewer.entities.add({
                name: '天宫' + i + "号\nID:star" + i,
                id: 'star' + i,

                orientation: orientation,
                position: mypos,


                cylinder: {
                    slices: 5,
                    length: 200000.0,
                    topRadius: 0.0,
                    //  middleRadius: 0.0,
                    bottomRadius: 50000.0,
                    material: Cesium.Color.RED
                }
                //   label: {  Cesium.Math.toRadians
                //       text: '天宫' + i + '号',
                //       font: '4pt monospace',
                //       style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                //       outlineWidth: 1,
                //       verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                //       pixelOffset: new Cesium.Cartesian2(0, 9)
                //   }
            });
        }
    };
    this.delstars = function() {
        var allitems = this.viewer.entities.values

        var count = allitems.length;
        for (var i = 0; i < count; i++) {
            var item = allitems[i]

            if (typeof(item) != 'undefined') {
                if (item.id.indexOf('star') >= 0) {
                    // this.viewer.entities.removeById(item.id)
                    this.viewer.entities.remove(item)
                }
            }

        }
    }

    var planePrimitive
    this.delfallowPlane = function() {
        this.fallowPlane_num = 0
        this.viewer.trackedEntity = undefined;
        myviewer.entities.remove(fallow_entityPath)
        myviewer.scene.primitives.remove(planePrimitive)
    };
    //旋转模型
    var test_addedmodel
    var polylinemodel
    this.ModelRotatetest_z = function() {
        var heading = Cesium.Math.toRadians(270);
        var pitch = Cesium.Math.toRadians(180);
        var rotation_z = Math.round(Math.random() * 360, 1)
        alert(rotation_z)
        var roll = Cesium.Math.toRadians(rotation_z);
        var hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        var fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator('north', 'west');

        var position = Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414, 0.0);

        // var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        //     Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414, 0.0));
        var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform)
        test_addedmodel.modelMatrix = modelMatrix
        polylinemodel.modelMatrix = modelMatrix
        test_addedmodel.name = 270 + '--' + 180 + '--' + rotation_z

        var ref = { 'polyline': polylinemodel }
        var onship = { 'position': position, 'ref': ref }
            // keepsizeModel.rotateOneShipShortcut(270, 180,
            //     rotation_z, myviewer.scene.globe.ellipsoid, onship, hpRoll, fixedFrameTransform)
    };
    this.ModelRotatetest_y = function() {
        var heading = Cesium.Math.toRadians(270);
        var y = Math.round(Math.random() * 360, 1)
        var pitch = Cesium.Math.toRadians(y)

        var roll = Cesium.Math.toRadians(0);
        var hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        var fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator('north', 'west');

        var position = Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414, 0.0);

        // var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        //     Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414, 0.0));
        var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform)
        test_addedmodel.modelMatrix = modelMatrix
        polylinemodel.modelMatrix = modelMatrix
        test_addedmodel.name = 270 + '--' + y + '--' + 90
        var ref = { 'polyline': polylinemodel }
        var onship = { 'position': position, 'ref': ref }
            // keepsizeModel.rotateOneShipShortcut(270, y,
            //     90, myviewer.scene.globe.ellipsoid, onship, hpRoll, fixedFrameTransform)
    };
    this.ModelRotatetest_x = function() {
        var x = Math.round(Math.random() * 360, 1)
        var heading = Cesium.Math.toRadians(x + 180)
        var pitch = Cesium.Math.toRadians(180);
        var roll = Cesium.Math.toRadians(270);
        var hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        var fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator('north', 'west');

        var position = Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414, 0.0);

        // var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        //     Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414, 0.0));
        var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform)
        test_addedmodel.modelMatrix = modelMatrix


        heading = Cesium.Math.toRadians(270 + x);
        pitch = Cesium.Math.toRadians(90);
        roll = Cesium.Math.toRadians(0);
        hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform)

        polylinemodel.modelMatrix = modelMatrix
        test_addedmodel.name = x + '--' + 180 + '--' + 90
        var ref = { 'polyline': polylinemodel }
        var onship = { 'position': position, 'ref': ref }
            // keepsizeModel.rotateOneShipShortcut(x, 180,
            //         90, myviewer.scene.globe.ellipsoid, onship, hpRoll, fixedFrameTransform)
            //polylinemodel  keepsizeModel
    };
    //添加模型primitives.add
    this.addModeltest = function() {

        var heading = Cesium.Math.toRadians(90 + 180);
        var pitch = Cesium.Math.toRadians(180);
        var roll = Cesium.Math.toRadians(270);
        var hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        var ellipsoid = myviewer.scene.globe.ellipsoid;


        var fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator('north', 'west');

        var position = Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414, 0.0);

        // var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        //     Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414, 0.0));
        var modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform)

        // pointPrimitives = myviewer.scene.primitives.add(new Cesium.PointPrimitiveCollection());
        test_addedmodel = myviewer.scene.primitives.add(Cesium.Model.fromGltf({
            //  url: '../Apps/SampleData/models/2CylinderEngine/2CylinderEngine.dae',
            id: heading + '--' + pitch + '--' + roll + ';' + -75.62898254394531 + ';' + 40.02804946899414 + ';' + position.z,
            name: heading + '--' + pitch + '--' + roll,
            //   url: '../Apps/SampleData/TriangleWithoutIndices/new/triangleug.gltf',
            // url: '../Apps/SampleData/TriangleWithoutIndices/new/polygon5ug.gltf',
            url: '../Apps/SampleData/TriangleWithoutIndices/new/polygon6ug.gltf',

            modelMatrix: modelMatrix,
            scale: 1.0, // double size
            color: Cesium.Color.RED,
            // maximumScale: 20000, // never larger than 20000 * model size (overrides minimumPixelSize)
            allowPicking: true, //   pickable
            minimumPixelSize: 58 * 1
        }));
        // myviewer.scene.primitives.add(polyline);
        myviewer.trackedEntity = test_addedmodel;

        // var boundingSphere_center = { x: 25000, y: 25000, z: 0 }
        // var next_ship_center = new Cesium.Cartesian3();

        heading = Cesium.Math.toRadians(180 + 180);
        pitch = Cesium.Math.toRadians(90);
        roll = Cesium.Math.toRadians(0);
        hpRoll = new Cesium.HeadingPitchRoll(heading, pitch, roll);
        //position = Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414, -70.0);
        modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform)
            // Cesium.Matrix4.multiplyByPoint(modelMatrix, boundingSphere_center, next_ship_center);
            // var cartographic = ellipsoid.cartesianToCartographic(next_ship_center);
            // var lng = Cesium.Math.toDegrees(cartographic.longitude);
            // var lat = Cesium.Math.toDegrees(cartographic.latitude);
            // var position_b = Cesium.Cartesian3.fromDegrees(lng, lat, 0.0);
            // modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position_b, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform)

        polylinemodel = myviewer.scene.primitives.add(Cesium.Model.fromGltf({
            //  url: '../Apps/SampleData/models/2CylinderEngine/2CylinderEngine.dae',
            id: 'speedline-' + heading + '--' + pitch + '--' + roll,
            name: 'speedline-' + heading + '--' + pitch + '--' + roll,
            url: '../Apps/SampleData/TriangleWithoutIndices/new/cylinderug2.gltf',
            //   url: '../Apps/SampleData/TriangleWithoutIndices/new/triangle.gltf',

            //   url: '../Apps/SampleData/TriangleWithoutIndices/glTF-Embedded/TriangleWithoutIndices.gltf',
            //  url: '../Apps/SampleData/Models/Box/Box.gltf',
            // url: '../Apps/SampleData/Models/Cube/glTF/Cube.gltf',

            modelMatrix: modelMatrix,
            scale: 1, // double size
            color: Cesium.Color.RED,
            // maximumScale: 20000, // never larger than 20000 * model size (overrides minimumPixelSize)
            allowPicking: true, //   pickable
            //航速线长度在此处控制
            minimumPixelSize: 80 * 1
        }));
        // var polylines = myviewer.scene.primitives.add(new Cesium.PolylineCollection());

    };
    //添加model entities.add 伸缩海图时大小会随之变化，不理想


    this.fallowPlane = function() {

        this.viewer.trackedEntity = undefined;
        var camera = myviewer.camera;
        if (this.fallowPlane_num >= 1) {

            camera.lookAt(fallow_plane_center, hpRange);
            //   myviewer.trackedEntity = plane_entity;
            return
        }
        this.fallowPlane_num += 1
            //   myviewer.trackedEntity = plane_entity;

        var canvas = myviewer.canvas;
        canvas.setAttribute('tabindex', '0'); // needed to put focus on the canvas
        canvas.addEventListener('click', function() {
            canvas.focus();
        });
        canvas.focus();
        var scene = myviewer.scene;
        var pathPosition_plane = new Cesium.SampledPositionProperty();
        fallow_entityPath = myviewer.entities.add({
            position: pathPosition_plane,
            name: 'path',
            entitytype: 'path',
            path: {
                show: true,
                leadTime: 0,
                trailTime: 60,
                width: 10,
                resolution: 1,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.3,
                    color: Cesium.Color.PALEGOLDENROD
                })
            }
        });


        var r = 0
            //  var fallow_plane_center = new Cesium.Cartesian3();
            //  var hpRange = new Cesium.HeadingPitchRange();
        var hpRoll = new Cesium.HeadingPitchRoll();

        //var speed = 100;
        var speed = 0;
        var deltaRadians = Cesium.Math.toRadians(3.0);
        //目标原始位置！！！！！
        var position = Cesium.Cartesian3.fromDegrees(-65.6244619, 43.3903706, 5000.0);
        var speedVector = new Cesium.Cartesian3();
        var fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator('north', 'west');

        planePrimitive = scene.primitives.add(Cesium.Model.fromGltf({
            url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.glb',
            //  url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.dae',
            // url: '../Apps/SampleData/RNPTBOAT35.dae',
            //   url: '../Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
            //将原始位置放入旋转矩阵
            modelMatrix: Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform),
            minimumPixelSize: 128 * 1
                // maximumScale: 128 * 1
        }));
        planePrimitive.readyPromise.then(function(model) {
            // Play and loop all animations at half-speed
            model.activeAnimations.addAll({
                speedup: 0.5,
                loop: Cesium.ModelAnimationLoop.REPEAT
            });

            // Zoom to model
            r = 2.0 * Math.max(model.boundingSphere.radius, camera.frustum.near);
            controller.minimumZoomDistance = r * 0.5;
            //fallow_plane_center这是求出旋转后的位置
            Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, fallow_plane_center);
            var heading = Cesium.Math.toRadians(230.0);
            var pitch = Cesium.Math.toRadians(-20.0);
            hpRange.heading = heading;
            hpRange.pitch = pitch;
            hpRange.range = r * 50.0;
            // hpRange.range = r * 100.0;
            camera.lookAt(fallow_plane_center, hpRange);
        });
        myviewer.trackedEntity = planePrimitive;
        //加了一个监听
        document.addEventListener('keydown', function(e) {

            switch (e.keyCode) {
                case 40:
                    if (e.shiftKey) {
                        // speed down  调整速度
                        //   speed = Math.max(--speed, 1);
                        speed -= 10
                    } else {
                        // pitch down
                        hpRoll.pitch -= deltaRadians;
                        if (hpRoll.pitch < -Cesium.Math.TWO_PI) {
                            hpRoll.pitch += Cesium.Math.TWO_PI;
                        }
                    }
                    break;
                case 38: //调整速度
                    if (e.shiftKey) {
                        // speed up
                        //   speed = Math.min(++speed, 100);
                        speed += 10
                    } else {
                        // pitch up
                        hpRoll.pitch += deltaRadians;
                        if (hpRoll.pitch > Cesium.Math.TWO_PI) {
                            hpRoll.pitch -= Cesium.Math.TWO_PI;
                        }
                    }
                    break;
                case 39:
                    if (e.shiftKey) {
                        // roll right
                        hpRoll.roll += deltaRadians;
                        if (hpRoll.roll > Cesium.Math.TWO_PI) {
                            hpRoll.roll -= Cesium.Math.TWO_PI;
                        }
                    } else {
                        // turn right
                        hpRoll.heading += deltaRadians;
                        if (hpRoll.heading > Cesium.Math.TWO_PI) {
                            hpRoll.heading -= Cesium.Math.TWO_PI;
                        }
                    }
                    break;
                case 37:
                    if (e.shiftKey) {
                        // roll left until
                        hpRoll.roll -= deltaRadians;
                        if (hpRoll.roll < 0.0) {
                            hpRoll.roll += Cesium.Math.TWO_PI;
                        }
                    } else {
                        // turn left
                        hpRoll.heading -= deltaRadians;
                        if (hpRoll.heading < 0.0) {
                            hpRoll.heading += Cesium.Math.TWO_PI;
                        }
                    }
                    break;
                default:
            }
        });
        var headingSpan = document.getElementById('heading');
        var pitchSpan = document.getElementById('pitch');
        var rollSpan = document.getElementById('roll');
        var speedSpan = document.getElementById('speed');


        var fromBehind = document.getElementById('fromBehind');
        //   myviewer.trackedEntity = plane_entity;
        myviewer.scene.preRender.addEventListener(function(scene, time) {
            headingSpan.innerHTML = Cesium.Math.toDegrees(hpRoll.heading).toFixed(1);
            pitchSpan.innerHTML = Cesium.Math.toDegrees(hpRoll.pitch).toFixed(1);
            rollSpan.innerHTML = Cesium.Math.toDegrees(hpRoll.roll).toFixed(1);
            speedSpan.innerHTML = speed.toFixed(1);
            //此处求出速度矢量，可以调整速度
            speedVector = Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_X, speed / 10, speedVector);
            //旋转+平移= 速度变化后的位置
            position = Cesium.Matrix4.multiplyByPoint(planePrimitive.modelMatrix, speedVector, position);
            pathPosition_plane.addSample(Cesium.JulianDate.now(), position);
            Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll, Cesium.Ellipsoid.WGS84, fixedFrameTransform, planePrimitive.modelMatrix);
            //锁定目标
            if (fromBehind.checked) {
                // Zoom to model
                // alert(fallow_plane_center.x + '--' + fallow_plane_center.y + '--' + fallow_plane_center.z)
                //求出飞机旋转平移后新的位置
                Cesium.Matrix4.multiplyByPoint(planePrimitive.modelMatrix, planePrimitive.boundingSphere.center, fallow_plane_center);
                //  alert(fallow_plane_center.x + '--' + fallow_plane_center.y + '--' + fallow_plane_center.z)
                //   hpRange.heading = hpRoll.heading;
                //   hpRange.pitch = hpRoll.pitch;
                //实时跟踪飞机的位置
                camera.lookAt(fallow_plane_center, hpRange);
                //   myviewer.trackedEntity = planePrimitive;
            }
        });






    }
    this.delShips = function() {

        // this.viewer.delShips()

        //  pointPrimitives = {}
        var res = myviewer.scene.primitives.remove(pointPrimitives)

        if (res) {
            this.g_ships.removeAllShapedShip(CylinderShipArr, swaparr, swapcount)
            swaparr = []

        }

        //destroyPointPrimitives
        //     myviewer.scene.primitives.removeAll()
        //
        this.fallowPlane_num = 0
            //   var container = myviewer.scene.primitives._primitives
            //   if (container.length > 0) {

        //       for (var i = 0; i < container.length; i++) {
        //           var PointPrimitiveCollection = container[i]
        //               // container[2]._pointPrimitives.removeAll()
        //           PointPrimitiveCollection._pointPrimitives = []
        //               //PointPrimitiveCollection.removeAll()
        //           PointPrimitiveCollection._billboards = []
        //           console.log(PointPrimitiveCollection)
        //       }

        //   }

        //   var allitems = this.viewer.entities.values

        //   var count = allitems.length;
        //   for (var i = 0; i < count; i++) {
        //       var item = allitems[i]

        //       if (typeof(item) != 'undefined') {
        //           if (item.id.indexOf('ship') >= 0) {
        //               // this.viewer.entities.removeById(item.id)
        //               this.viewer.entities.remove(item)
        //           }
        //       }

        //   }


    };
    this.addshipsAgain = function() {
        var czml
        var shipcount = 210000
        var rotation = 360 * Math.random()
        var r = rotation / 180 * Math.PI;
        var cosValue = Math.cos(r);
        var sinValue = Math.sin(r);

        var e = 18000000;
        var type = 1;
        var onet = {
            "id": "document2",
            "name": "CZML Point2",
            "version": "2.0"
        }
        czml = czml || []
        czml.push(onet)
        var ship;
        for (var j = 110001; j < shipcount; j++) {
            ship = {
                "id": "ship" + j,
                "name": '渔船p' + j + '\nID:ship' + j,
                "position": {
                    "cartographicDegrees": [2 * e * Math.random() - e,
                        2 * e * Math.random() - e, 0
                    ]
                },
                "point": {
                    "color": {
                        "rgba": [255, 255, 255, 255]
                    },
                    "outlineColor": {
                        "rgba": [255, 0, 0, 255]
                    },
                    "outlineWidth": 1,
                    "pixelSize": 3
                }
            }
            czml.push(ship)
        }




        var dataSourcePromise = Cesium.CzmlDataSource.load(czml);
        myviewer.dataSources.add(dataSourcePromise);

        //   myviewer.zoomTo(dataSourcePromise);
        /*
        for (var j = 0; j < shipcount; j++) {
            if (type == 0) {
                var ship = this.viewer.entities.add({
                    name: '渔船p' + j + '\nID:ship' + j,
                    id: 'ship' + j,
                    position: Cesium.Cartesian3.fromDegrees(
                        // 175.166493 * Math.random(), -139.9060534 * Math.random(), 0
                        2 * e * Math.random() - e,
                        2 * e * Math.random() - e, 0
                    ),
                    point: {
                        pixelSize: 3,
                        color: Cesium.Color.ORANGE,
                        outlineColor: Cesium.Color.ORANGE,
                        outlineWidth: 1
                    }
                });
                //this.rotateme = new Cesium.rotateme(testarr, rotation)
                this.g_ships.storeShip(ship)
                type = 1
            } else {
                var ship = this.viewer.entities.add({
                    name: '渔船p' + j + '\nID:ship' + j,
                    id: 'ship' + j,
                    position: Cesium.Cartesian3.fromDegrees(
                        // -175.166493 * Math.random(), 139.9060534 * Math.random(), 0
                        2 * e * Math.random() - e,
                        2 * e * Math.random() - e, 0
                    ),
                    point: {
                        pixelSize: 3,
                        color: Cesium.Color.YELLOW,
                        outlineColor: Cesium.Color.YELLOW,
                        outlineWidth: 1
                    }
                });
                //this.rotateme = new Cesium.rotateme(testarr, rotation)
                this.g_ships.storeShip(ship)
                type = 0
            }
        }
        */



    };
    //测试




    //填充数据
    var mainChinaCity = []
    var swap = -1
    var swapcount = 1500
    var swaparr
    swaparr = swaparr || []
    // var swaparr_inside
    // swaparr_inside = swaparr_inside || []
    var e1 = 18000000;

    var shapetype
    var shipcolor = Cesium.Color.PURPLE

    //
    this.initMainChinaCity = function() {
        var temp = []
        var beijin = { 'x': 116.41667, 'y': 39.91667 }
        var shanghai = { 'x': 121.43333, 'y': 34.50000 }
        var tianjin = { 'x': 117.20000, 'y': 39.13333 }
        var hangkang = { 'x': 114.10000, 'y': 22.20000 }
        var guangzhou = { 'x': 113.23333, 'y': 23.16667 }
        var zhuhai = { 'x': 113.51667, 'y': 22.30000 }
        var shenzhen = { 'x': 114.06667, 'y': 22.61667 }
        var hangzhou = { 'x': 116.41667, 'y': 39.91667 }
        temp.push(beijin)
        temp.push(shanghai)
        temp.push(tianjin)
        temp.push(hangkang)
        temp.push(guangzhou)
        temp.push(zhuhai)
        temp.push(shenzhen)
        temp.push(hangzhou)
        for (var j = 0; j < temp.length; ++j) {
            var position = new Cesium.Cartesian3.fromDegrees(temp[j].x, temp[j].y, 0)
            var shipbundle = {
                'x': temp[j].x,
                'y': temp[j].y,
                'position': position,
                'isPointInstall': false,
                'isShapedInstall': false,
                'levelId': 1,
                'levelName': 'city',
                'myball': ''
            }
            mainChinaCity.push(shipbundle)
        }


    };
    this.addCicleHallow = function() {
        for (var j = 0; j < mainChinaCity.length; ++j) {
            debugger
            var oneship = mainChinaCity[j]
            this.createPrimitives(myviewer.scene, myviewer.scene.globe.ellipsoid, oneship.x, oneship.y);
        }

    }; //116.47, 39.23
    this.initRoundShips = function() {
        // myviewer.scene.primitives.removeAll()
        var rotation
        var sponser
        var base = myviewer.scene.globe.ellipsoid.radii.x;
        document.getElementById("ship_amt").innerHTML = swapcount;
        for (var j = 0; j < swapcount; ++j) {
            var x = Math.random()
                //_focus
                // var position = new Cesium.Cartesian3.fromDegrees(75.59777 * Math.random() / 4, 40.03883 * Math.random() / 4)
                //_spreadwholeEarth

            // var px0 = 2 * e1 * Math.random() - e1;
            // var py0 = 2 * e1 * Math.random() - e1;

            // var px0 = 116.73 + Math.random() * 10
            // var py0 = 39.87 + Math.random() * 6

            // var px0 = 107.73 + Math.random() * 10
            // var py0 = 33.87 + Math.random() * 6
            var jijing= 10   //极半径
            
            var px0 = 107.73 + jijing*Math.random() * Math.cos(Math.random()*6.28)
            var py0 = 33.87 +  jijing*Math.random() * Math.sin(Math.random()*6.28)
             
            if (px0 > 180) {
                px0 -= 180
            } else if (px0 < -180) {
                px0 += 180
            }
            if (py0 > 90) {
                py0 -= 90
            } else if (py0 < -90) {
                py0 += 90
            }
            if (j > swapcount / 2) {
                px0 = -17.73 * Math.random() * 10
                py0 = -25.87 * Math.random() * 7
                if (px0 > 180) {
                    px0 -= 180
                } else if (px0 < -180) {
                    px0 += 180
                }
                if (py0 > 90) {
                    py0 -= 90
                } else if (py0 < -90) {
                    py0 += 90
                }
            }
            var position = new Cesium.Cartesian3.fromDegrees(px0, py0, 0)

            rotation = Math.round(Math.random() * 360)
                //new Cesium.Cartesian3.fromDegrees(
                // 2 * e1 * x - e1,
                // 2 * e1 * x - e1, 0);
            if (j % 3 == 0) {
                shapetype = 'five'
                sponser='张3'
                shipcolor = Cesium.Color.PURPLE
            } else if (j % 3 == 1) {
                shapetype = 'three'
                sponser='李四'
                shipcolor = Cesium.Color.BLUE
            } else if (j % 3 == 2) {
                shapetype = 'six'
                sponser='王五'
                shipcolor = Cesium.Color.ORANGE
            } else {
                shapetype = 'six'
                sponser='赵六'
                shipcolor = Cesium.Color.ORANGE
            }
            shipcolor = Cesium.Color(52, 52, 52, 0.5)  //不起作用
            var shipbundle = {
                'x': px0,
                'y': py0,
                'sponser': sponser,
                'shiptype': shapetype,
                'rotation': rotation,
                'position': position,
                'shipcolor': shipcolor,
                'outlineColor': Cesium.Color.GREEN,
                'isPointInstall': false,
                'isShapedInstall': false,
                'myball': ''
            }
            swaparr.push(shipbundle)
        //    swaparr_inside.push(shipbundle)
        }

    };

    this.createPrimitives = function(scene, ellipsoid, x, y) {
        debugger
        var primitives = scene.primitives;

        var outerPositions = Cesium.Shapes.computeCircleBoundary(
            ellipsoid,
            ellipsoid.cartographicToCartesian(Cesium.Cartographic.fromDegrees(x, y)),
            300000.0);
        var innerPositions = Cesium.Shapes.computeCircleBoundary(
            ellipsoid,
            ellipsoid.cartographicToCartesian(Cesium.Cartographic.fromDegrees(x, y)),
            200000.0);
        var hierarchy = {
            positions: outerPositions,
            holes: [{
                positions: innerPositions
            }]
        };
        var circle = new Cesium.Polygon({
            polygonHierarchy: hierarchy
        });
        circle.material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 0.5);
        primitives.add(circle);

    }
    this.addCicleUg = function() {
        var t = 0
        var e = 18000000;
        var oneship
            // var color = Cesium.Color.fromCssColorString('#FFFFFF');; //#FFFFFF
        var color = Cesium.Color.TRANSPARENT; //#FFFFFF
        var outlineColor = Cesium.Color.fromCssColorString('#40E0D0');
        for (var j = 0; j < mainChinaCity.length; ++j) {
            switch (t) {
                case 0:
                    outlineColor = Cesium.Color.fromCssColorString('#A52A2A'); //／／.withAlpha(0.3)
                    t = 1
                    break;
                case 1:
                    outlineColor = Cesium.Color.fromCssColorString('#7FFF00');
                    t = 2
                    break;
                case 2:
                    outlineColor = Cesium.Color.fromCssColorString('#DC143C');
                    t = 0
                    break;
            }
            oneship = mainChinaCity[j]
            var ellipseOutlineGeometry = new Cesium.EllipseOutlineGeometry({
                center: Cesium.Cartesian3.fromDegrees(oneship.x, oneship.y),
                semiMinorAxis: 30000.0,
                semiMajorAxis: 30000.0
            });
            var ellipseOutlineInstance = new Cesium.GeometryInstance({
                geometry: ellipseOutlineGeometry,
                attributes: {
                    color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.WHITE)
                }
            });

            ellipseOutlineGeometry = new Cesium.EllipseOutlineGeometry({
                center: Cesium.Cartesian3.fromDegrees(oneship.x, oneship.y),
                semiMinorAxis: 20000.0,
                semiMajorAxis: 30000.0,
                extrudedHeight: 15000.0,
                rotation: Cesium.Math.toRadians(0),
                numberOfVerticalLines: 100
            });
            var extrudedEllipseOutlineInstance = new Cesium.GeometryInstance({
                geometry: ellipseOutlineGeometry,
                attributes: {
                    color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.WHITE)
                }
            });

            myviewer.scene.primitives.add(new Cesium.Primitive({
                geometryInstances: [ellipseOutlineInstance, extrudedEllipseOutlineInstance],
                appearance: new Cesium.PerInstanceColorAppearance({
                    flat: true,
                    renderState: {
                        lineWidth: Math.min(20.0, 55)
                    }
                })
            }));
        }
    };
    this.addCicle = function() {
        var t = 0
        var e = 18000000;
        var oneship
            // var color = Cesium.Color.fromCssColorString('#FFFFFF');; //#FFFFFF
        var color = Cesium.Color.TRANSPARENT; //#FFFFFF
        var outlineColor = Cesium.Color.fromCssColorString('#008B8B');
        for (var j = 0; j < mainChinaCity.length; ++j) {
            switch (t) {
                case 0:
                    outlineColor = Cesium.Color.fromCssColorString('#006400'); //／／.withAlpha(0.3)
                    t = 1
                    break;
                case 1:
                    outlineColor = Cesium.Color.fromCssColorString('#BDB76B');
                    t = 2
                    break;
                case 2:
                    outlineColor = Cesium.Color.fromCssColorString('#483D8B');
                    t = 0
                    break;
            }
            oneship = mainChinaCity[j]

            var greenCircle = myviewer.entities.add({
                position: Cesium.Cartesian3.fromDegrees(oneship.x, oneship.y, 0),
                name: 'Green circle at height with outline',
                ellipse: {
                    semiMinorAxis: 30000.0,
                    semiMajorAxis: 30000.0,
                    height: 0.0,
                    material: Cesium.Color.TRANSPARENT,
                    outlineColor: outlineColor,
                    outlineWidth: 10,
                    outline: true // height must be set for outline to display
                }
            });
            greenCircle = myviewer.entities.add({
                position: Cesium.Cartesian3.fromDegrees(oneship.x, oneship.y, 0),
                name: 'Green circle at height with outline',
                ellipse: {
                    semiMinorAxis: 20000.0,
                    semiMajorAxis: 20000.0,
                    height: 0.0,
                    material: Cesium.Color.TRANSPARENT,
                    outlineColor: outlineColor,
                    outlineWidth: 10,
                    outline: true // height must be set for outline to display
                }
            });
            // var circleGeometryBase = new Cesium.CircleGeometry({
            //     center: Cesium.Cartesian3.fromDegrees(oneship.x, oneship.y, 1.0),
            //     radius: 300000.0,
            //     vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
            // });
            // var redCircleInstanceBase = new Cesium.GeometryInstance({
            //     geometry: circleGeometryBase,
            //     attributes: {
            //         color: Cesium.ColorGeometryInstanceAttribute.fromColor(outlineColor)
            //     }
            // });
            // myviewer.scene.primitives.add(new Cesium.Primitive({
            //     geometryInstances: [redCircleInstanceBase],
            //     appearance: new Cesium.PerInstanceColorAppearance({
            //         closed: false
            //     })
            // }));
            // var insideCircle = myviewer.entities.add({
            //     name: 'Red cone',
            //     position: Cesium.Cartesian3.fromDegrees(oneship.x, oneship.y, 0.0),
            //     cylinder: {
            //         length: 50.0,
            //         topRadius: 20000.0,
            //         bottomRadius: 20000.0,
            //         material: outlineColor
            //     }
            // });
            var circleGeometry = new Cesium.CircleGeometry({
                center: Cesium.Cartesian3.fromDegrees(oneship.x, oneship.y, 0.0),
                radius: 10000.0,
                // outlineColor: Cesium.Color.fromCssColorString('#FFFFFF'),
                // outlineWidth: 1000,
                outline: false,
                vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
            });
            var redCircleInstance = new Cesium.GeometryInstance({
                geometry: circleGeometry,
                // outlineColor: Cesium.Color.fromCssColorString('#FFFFFF'),
                // outlineWidth: 1000,
                outline: false,
                attributes: {
                    color: Cesium.ColorGeometryInstanceAttribute.fromColor(outlineColor)
                }
            });
            myviewer.scene.primitives.add(new Cesium.Primitive({
                geometryInstances: [redCircleInstance],
                appearance: new Cesium.PerInstanceColorAppearance({
                    closed: false
                })
            }));
            // var insideCircle = myviewer.entities.add({
            //     position: Cesium.Cartesian3.fromDegrees(oneship.x, oneship.y, 0),
            //     name: 'Green circle at height with outline',
            //     ellipse: {
            //         semiMinorAxis: 20000.0,
            //         semiMajorAxis: 20000.0,
            //         height: 0.0,
            //         outlineColor: Cesium.Color.fromCssColorString('#FFFFFF'),
            //         material: outlineColor,
            //         outlineWidth: 10000,
            //         outline: true // height must be set for outline to display
            //     }
            // });

        }




    }



    //   var keepsizedShipArr;
    //   keepsizedShipArr = keepsizedShipArr || []

    /**
     * init the CylinderShipArr.
     * @memberof
     * @type
     * @readonly
     */
    this.initCylinderShip = function() {
        var shipcount = 0
        var testarr = []
        var five_sixe_rate = 100
        var rotation_x = 270
        var rotation_y = -90
        var rotation_z = 0
        CylinderShipArr = CylinderShipArr || []

    }




    var questionPin

    this.delPinBuilder = function() {

        myviewer.entities.remove(questionPin)

    }
    this.addPinBuilder = function() {
        var pinBuilder = new Cesium.PinBuilder();



        questionPin = myviewer.entities.add({
            name: '测试2',
            entitytype: 'questionPin',
            position: Cesium.Cartesian3.fromDegrees(-75.1698529, 39.9220071),
            billboard: {
                image: pinBuilder.fromText('?', Cesium.Color.BLACK, 48).toDataURL(),
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM
            }
        });
        this.viewer.trackedEntity = questionPin
            //   var url = Cesium.buildModuleUrl('Assets/Textures/maki/grocery.png');
            //   groceryPin = Cesium.when(pinBuilder.fromUrl(url, Cesium.Color.GREEN, 48), function(canvas) {
            //       return myviewer.entities.add({
            //           name: '测试3',
            //           position: Cesium.Cartesian3.fromDegrees(-85.1705217, 39.921786),
            //           billboard: {
            //               image: canvas.toDataURL(),
            //               verticalOrigin: Cesium.VerticalOrigin.BOTTOM
            //           }
            //       });
            //   });

        //   //Create a red pin representing a hospital from the maki icon set.
        //   hospitalPin = Cesium.when(pinBuilder.fromMakiIconId('hospital', Cesium.Color.RED, 48), function(canvas) {
        //       return myviewer.entities.add({
        //           name: '测试4',
        //           position: Cesium.Cartesian3.fromDegrees(-55.1698606, 39.9211275),
        //           billboard: {
        //               image: canvas.toDataURL(),
        //               verticalOrigin: Cesium.VerticalOrigin.BOTTOM
        //           }
        //       });
        //   });

    };
    var toolbar
    this.addGeoPlot = function() {
        popUpLonLatDiv('marker')
        document.getElementById("marker").click();
        // drawHelper.startDrawingPlot();
    };
    this.initDrawHelper = function() {
        toolbar = drawHelper.addToolbar(document.getElementById("shapetoolbar"), {
            buttons: ['marker', 'polyline', 'polygon', 'circle', 'extent']
        });
        //此处包含部分编辑图形功能
        toolbar.addListener('markerCreated', function(event) {
            loggingMessage('点物标创建在 ' + event.position.toString());
            // create one common billboard collection for all billboards
            var b = new Cesium.BillboardCollection();
            myviewer.scene.primitives.add(b);
            var shapeuuid = tool.getUUID()
            var billboard = b.add({
                show: true,
                id: shapeuuid,
                entitytype: '点物标',
                position: event.position,
                pixelOffset: new Cesium.Cartesian2(0, 0),
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.CENTER,
                scale: 1.0,
                image: '../ThirdParty/img/glyphicons_242_google_maps.png',
                color: Cesium.Color.RED
            });
            billboard.setEditable();
            billboard.addListener('onEdited', function(event) {
                //RegetDrawObjPos(position) //from drawHelperEtc.js
                loggingMessage('marker edited, ' + event.position[0]);
            })
            var labeluuid = tool.getUUID()
            document.getElementById("curr_shapeUniqeId").innerHTML = labeluuid;
            // Label 添加描述
            var label = myviewer.entities.add({
                id: labeluuid,
                entitytype: 'label',
                position: event.position,
                label: {

                    // This callback updates the length to print each frame.
                    text: 'markerCreated',
                    font: '20px sans-serif',
                    pixelOffset: new Cesium.Cartesian2(0.0, 20)
                }
            });

            var obj = {

                'labeluuid': labeluuid,
                'shapeuuid': shapeuuid,
                'shape': billboard,
                'type': 'point',
                'event': event,
                'obj': label

            }
            drawHelper.addShape(obj)
        });
        toolbar.addListener('polylineCreated', function(event) {
            loggingMessage('Polyline created with ' + event.positions.length + ' points');
            var shapeuuid = tool.getUUID()
            var polyline = new Cesium.PolylinePrimitive({
                id: shapeuuid,
                entitytype: '线物标',
                positions: event.positions,
                width: 5,
                geodesic: true
            });
            myviewer.scene.primitives.add(polyline);
            polyline.setEditable();
            polyline.addListener('onEdited', function(event) {
                loggingMessage('Polyline edited, ' + event.positions.length + ' points');
                //编辑完后，更新经纬度列表用
                RegetDrawObjPos(event.positions) //from drawHelperEtc.js
            });
            var labeluuid = tool.getUUID()
            document.getElementById("curr_shapeUniqeId").innerHTML = labeluuid;
            // Label 添加描述
            var label = myviewer.entities.add({
                id: labeluuid,
                entitytype: 'label',
                position: event.positions[0],
                label: {

                    // This callback updates the length to print each frame.
                    text: 'polylineCreated',
                    font: '20px sans-serif',
                    pixelOffset: new Cesium.Cartesian2(0.0, 20)
                }
            });

            var obj = {

                'labeluuid': labeluuid,
                'shapeuuid': shapeuuid,
                'shape': polyline,
                'type': 'polyline',
                'event': event,
                'obj': label
            }
            drawHelper.addShape(obj)
        });
        //触发围栏搜索
        toolbar.addListener('polygonCreated', function(event) {


            /*
            行列式解法
            pts = {{x1, y1}, {x2, y2}, {x3, y3}};(*定义三点坐标*)
            deter = PadLeft[pts, {3, 3}, 1];
            area1 = 1/2 Abs[Det[deter]]
            */
            // loggingMessage('Polygon created with ' + event.positions.length + ' points');
            var shapeuuid = tool.getUUID()
            var polygon = new Cesium.PolygonPrimitive({
                id: shapeuuid,
                entitytype: '面物标',
                positions: event.positions,
                material: Cesium.Material.fromType('Checkerboard')
            });
            myviewer.scene.primitives.add(polygon);
            var area = tool.countAreak(polygon.positions)
                // var area = tool.countArea(polygon)
                //  var area = tool.countAreaUg(polygon)
            loggingMessage('面积:' + area);
            //围栏搜索
            var retShipInfo = shapedSearch.ShapedSearch(swaparr, polygon, 'polygon')

            if (retShipInfo.length > 0) {
                alert('在多边形内的目标数量为' + retShipInfo.length)
                    //  ReturnOnMouseRightDownB(retShipInfo)
            }

            polygon.setEditable();
            polygon.addListener('onEdited', function(event) {
                loggingMessage('Polygon edited, ' + event.positions.length + ' points');
                //编辑完后，更新经纬度列表用
                retShipInfo = shapedSearch.ShapedSearch(swaparr, polygon, 'polygon')
                RegetDrawObjPos(event.positions)

                if (retShipInfo.length > 0) {
                    alert('在多边形内的目标数量为' + retShipInfo.length)
                        //  ReturnOnMouseRightDownB(retShipInfo)
                }
                //from drawHelper.js
            });
            // Label 添加描述
            var labeluuid = tool.getUUID()
            document.getElementById("curr_shapeUniqeId").innerHTML = labeluuid;
            // Label 添加描述
            var label = myviewer.entities.add({
                id: labeluuid,
                entitytype: 'label',
                position: event.positions[0],
                label: {

                    // This callback updates the length to print each frame.
                    text: 'polygonCreated',
                    font: '20px sans-serif',
                    pixelOffset: new Cesium.Cartesian2(0.0, 20)
                }
            });

            var obj = {
                'labeluuid': labeluuid,
                'shapeuuid': shapeuuid,
                'shape': polygon,
                'type': 'polygon',
                'event': event,
                'obj': label
            }
            drawHelper.addShape(obj)

        });

        toolbar.addListener('sectorCreated', function(event) {

            var shapeuuid = tool.getUUID()
            var polygon = new Cesium.PolygonPrimitive({
                id: shapeuuid,
                entitytype: '面物标',
                positions: event.positions,
                material: Cesium.Material.fromType(Cesium.Material.RimLightingType)
                    // material: Cesium.Material.fromType('Checkerboard')
            });
            myviewer.scene.primitives.add(polygon);
            var area = tool.countArea(polygon)
                //围栏搜索
            var retShipInfo = shapedSearch.ShapedSearch(swaparr, polygon, 'sector')
            if (retShipInfo.length > 0) {
                alert('在多边形内的目标数量为' + retShipInfo.length)
                    //  ReturnOnMouseRightDownB(retShipInfo)
            }
            polygon.setEditable();
            polygon.addListener('onEdited', function(event) {
                //  loggingMessage('面积:' + area);
                //围栏搜索
                var retShipInfo = shapedSearch.ShapedSearch(swaparr, polygon, 'sector')
                if (retShipInfo.length > 0) {
                    alert('在多边形内的目标数量为' + retShipInfo.length)
                        //  ReturnOnMouseRightDownB(retShipInfo)
                }
                loggingMessage('sector edited, ' + event.positions.length + ' points' + ';面积:' + area);
                //编辑完后，更新经纬度列表用
                RegetDrawObjPos(event.positions) //from drawHelperEtc.js
            });
            //loggingMessage('面积:' + area);
            loggingMessage('sector created with ' + event.positions.length + ' points');
            var labeluuid = tool.getUUID()
            document.getElementById("curr_shapeUniqeId").innerHTML = labeluuid;
            // Label 添加描述
            var label = myviewer.entities.add({
                id: labeluuid,
                entitytype: 'label',
                position: event.positions[0],
                label: {

                    // This callback updates the length to print each frame.
                    text: 'sectorCreated',
                    font: '20px sans-serif',
                    pixelOffset: new Cesium.Cartesian2(0.0, 20)
                }
            });

            var obj = {
                'labeluuid': labeluuid,
                'shapeuuid': shapeuuid,
                'shape': polygon,
                'type': 'sector',
                'event': event,
                'obj': label
            }
            drawHelper.addShape(obj)

        });
        toolbar.addListener('circleCreated', function(event) {
            var radius = 0
            if (Cesium.defined(event.radius)) {
                radius = event.radius.toFixed(1)
            }
            var shapeuuid = tool.getUUID()
            loggingMessage('Circle created: center is ' + event.center.toString() + ' and radius is ' + radius + ' meters');
            var circle = new Cesium.CirclePrimitive({
                id: shapeuuid,
                entitytype: '圆物标',
                center: event.center,
                radius: event.radius,
                material: Cesium.Material.fromType(Cesium.Material.RimLightingType)
            });
            myviewer.scene.primitives.add(circle);
            //围栏搜索
            var retShipInfo = shapedSearch.ShapedSearch(swaparr, circle, 'circle')
            if (retShipInfo.length > 0) {
                alert('在多边形内的目标数量为' + retShipInfo.length)
                    //  ReturnOnMouseRightDownB(retShipInfo)
            }
            circle.setEditable();
            circle.addListener('onEdited', function(event) {
                RegetDrawObjRadius(event.radius) //from drawHelper.js
                    //围栏搜索
                var retShipInfo = shapedSearch.ShapedSearch(swaparr, circle, 'circle')
                if (retShipInfo.length > 0) {
                    alert('在多边形内的目标数量为' + retShipInfo.length)
                        //  ReturnOnMouseRightDownB(retShipInfo)
                }
                loggingMessage('Circle edited: radius is ' + radius + ' meters');
            });
            var labeluuid = tool.getUUID()

            document.getElementById("curr_shapeUniqeId").innerHTML = labeluuid;
            // Label 添加描述

            var label = myviewer.entities.add({
                id: labeluuid,
                entitytype: 'label',
                position: event.center,
                label: {
                    // This callback updates the length to print each frame.
                    text: 'circleCreated',
                    font: '20px sans-serif',
                    pixelOffset: new Cesium.Cartesian2(0.0, 20)
                }
            });

            var obj = {
                'labeluuid': labeluuid,
                'shapeuuid': shapeuuid,
                'shape': circle,
                'type': 'circle',
                'event': event,
                'obj': label
            }
            drawHelper.addShape(obj)
        });
        toolbar.addListener('extentCreated', function(event) {
            var extent = event.extent;
            var shapeuuid = tool.getUUID()
            loggingMessage('Extent created (N: ' + extent.north.toFixed(3) + ', E: ' + extent.east.toFixed(3) + ', S: ' + extent.south.toFixed(3) + ', W: ' + extent.west.toFixed(3) + ')');
            var extentPrimitive = new Cesium.ExtentPrimitive({
                id: shapeuuid,
                // text: 'rect created',

                entitytype: '矩形物标',
                extent: extent,
                material: Cesium.Material.fromType(Cesium.Material.StripeType)
            });
            myviewer.scene.primitives.add(extentPrimitive);

            //围栏搜索
            var retShipInfo = shapedSearch.ShapedSearch(swaparr, extentPrimitive, 'rect')
            if (retShipInfo.length > 0) {
                alert('在多边形内的目标数量为' + retShipInfo.length)
                    //  ReturnOnMouseRightDownB(retShipInfo)
            }

            var labeluuid = tool.getUUID()
            document.getElementById("curr_shapeUniqeId").innerHTML = labeluuid;

            extentPrimitive.setEditable();
            var corners = drawHelper.getExtentCornersB(extent);
            extentPrimitive.addListener('onEdited', function(event) {
                debugger
                //没必要popUpLonLatDiv()  //from drawHelperEtc.js
                var ddd = extentPrimitive.updateRect(event.extent, event.extent, myviewer.scene.globe.ellipsoid)
                GetCurDrawRectagleInfoUg(ddd.myfirstPoint, ddd.widthDis, ddd.heightDis, ddd.secondPoint)
                    //围栏搜索
                var retShipInfo = shapedSearch.ShapedSearch(swaparr, extentPrimitive, 'rect')
                if (retShipInfo.length > 0) {
                    alert('在多边形内的目标数量为' + retShipInfo.length)
                        //  ReturnOnMouseRightDownB(retShipInfo)
                }
                //   RegetExtendWidthLengthEtc(ddd.myfirstPoint, ddd.WidthDis, ddd.HeightDis) //from drawHelperEtc.js
                loggingMessage('Extent edited: extent is (N: ' + event.extent.north.toFixed(3) + ', E: ' + event.extent.east.toFixed(3) + ', S: ' + event.extent.south.toFixed(3) + ', W: ' + event.extent.west.toFixed(3) + ')');
            });

            // Label 添加描述

            var label = myviewer.entities.add({
                id: labeluuid,
                entitytype: 'label',
                position: corners[0],
                label: {
                    // This callback updates the length to print each frame.
                    text: 'rectCreated',
                    font: '20px sans-serif',
                    pixelOffset: new Cesium.Cartesian2(0.0, 20)
                }
            });
            var obj = {
                'labeluuid': labeluuid,
                'shapeuuid': shapeuuid,
                'shape': extentPrimitive,
                'type': 'rect',
                'event': event,
                'obj': label
            }
            drawHelper.addShape(obj)
        });

    };
    this.AddCurDrawObjectDD = function() {

        var objType = document.getElementById("drawObjType").value;
        var strName = document.getElementById("drawObjName").value;
        var objContent = document.getElementById("drawObjContent").value;
        var currUUid = document.getElementById("curr_shapeUniqeId").innerHTML
            // var arrObjPo = API_GetCurDrawDynamicObjGeoPo(); //这里坐标从组件中获取，假如要修改的话，就不能这样获取了，只能从物标信息面板中获取
            // var drawObjPoNum = arrObjPo.length;
        if (strName == "") {
            alert("请输入矩形的名称");
            return;
        }
        var bResult = true;



        if (bResult == true) {


            var ent = drawHelper.findShape(currUUid, 'pointlineface')

            ent.obj._label._text._value = strName

            CloseDivBox("drawObjBox");
        } else {
            alert("添加失败");
        }
    };
    this.AddCurDrawRectObjectDD = function() {
        var strName = document.getElementById("curDrawRectName").value;
        var strGeoPos = document.getElementById("curDrawRectGeoPo").innerHTML;
        var hailiWidthDis = document.getElementById("curDrawRectWidthDis").innerHTML;
        var hailiHeightDis = document.getElementById("curDrawRectHeightDis").innerHTML;
        var currUUid = document.getElementById("curr_shapeUniqeId").innerHTML
        if (strName == "") {
            alert("请输入矩形的名称");
            return;
        }
        var bResult = true;



        if (bResult == true) {


            var ent = drawHelper.findShape(currUUid, 'rect')

            ent.obj._label._text._value = strName

            CloseDivBox("DrawRectInfoDiv");
        } else {
            alert("添加矩形失败");
        }
    };
    this.AddCurDrawCircleObjectDD = function() {
        var strName = document.getElementById("curDrawCircleName").value;
        var strGeoPos = document.getElementById("curDrawCircleGeoPo").innerHTML;
        var hailiRDis = document.getElementById("curDrawCircleR").innerHTML;
        var currUUid = document.getElementById("curr_shapeUniqeId").innerHTML
        if (strName == "") {
            alert("请输入圆的名称");
            return;
        }
        var bResult = true;



        if (bResult == true) {

            var ent = drawHelper.findShape(currUUid, 'circle')
            ent.obj._label._text._value = strName

            CloseDivBox("DrawCircleInfoDiv");
        } else {
            alert("添加圆失败");
        }
    }

    function CloseDivBox(divBoxId) {
        var obj = document.getElementById(divBoxId);
        if (obj) {
            obj.style.display = "none";
        }
    }
    this.delAlarm = function () {
        for(var i=0; i<swaparr.length; i++){
            if(i%3==0){
             
             swaparr[i].myball.  outlineWidth = 0
            } else if(i%5==0){
            
             swaparr[i].myball.  outlineWidth = 0
            }  else if(i%7==0){
                swaparr[i].myball.  outlineWidth = 0
            }
        }
    }
    this.showAlarm = function () {
        //alarmmsg
        for(var i=0; i<swaparr.length; i++){
            if(i%3==0){
             swaparr[i].myball.outlineColor=Cesium.Color.YELLOW
             swaparr[i].myball.Color=Cesium.Color.YELLOW
             swaparr[i].myball.alarmmsg='故障'
             swaparr[i].myball.  outlineWidth = 4
            } else if(i%5==0){
             swaparr[i].myball.outlineColor=Cesium.Color.RED
             swaparr[i].myball.Color=Cesium.Color.RED
             swaparr[i].myball.alarmmsg='报警'
             swaparr[i].myball.  outlineWidth = 4
            }
             else if(i%7==0){
                swaparr[i].myball.outlineColor=Cesium.Color.GREEN
                swaparr[i].myball.Color=Cesium.Color.GREEN
                swaparr[i].myball.alarmmsg='上线'
                swaparr[i].myball.  outlineWidth = 4
            }
            else{
                swaparr[i].myball.alarmmsg='下线'
            }
        }
    }
    this.addShipHighspeed = function() {

        var t = 0
        var e = 18000000;
        pointPrimitives = myviewer.scene.primitives.add(new Cesium.PointPrimitiveCollection());
        var base = myviewer.scene.globe.ellipsoid.radii.x;
        var color = Cesium.Color.TRANSPARENT;; //#FFFFFF
        var outlineColor = Cesium.Color.fromCssColorString('#8FBC8F');
        var oneship

        var ellipsoid = myviewer.scene.globe.ellipsoid;


        for (var j = 0; j < swaparr.length; ++j) {
            switch (t) {
                case 0:
                    outlineColor = Cesium.Color.fromCssColorString('#cccccc'); //／  #00CED1 .withAlpha(0.3)
                    t = 1
                    break;
                case 1:
                    outlineColor = Cesium.Color.fromCssColorString('#cccccc'); //9400D3
                    t = 2
                    break;
                case 2:
                    outlineColor = Cesium.Color.fromCssColorString('#cccccc');//FF1493
                    t = 0
                    break;
            }
            oneship = swaparr[j]
                //   var position = new Cesium.Cartesian3(
                //       16000000 * Math.random() - 8000000, -(4000000 * j / swaparr.length + base),
                //       2000000 * Math.random() - 1000000);
                //   var position = new Cesium.Cartesian3.fromDegrees(
                //       2 * e * Math.random() - e,
                //       2 * e * Math.random() - e, 0);

            // var cartesian3 = Cesium.Cartesian3.fromDegrees(oneship.position.x, oneship.position.y, oneship.position.z);
            // var cartographic = ellipsoid.cartesianToCartographic(cartesian3);
            // var lat = Cesium.Math.toDegrees(cartographic.latitude);
            // var lng = Cesium.Math.toDegrees(cartographic.longitude);

            var ball = pointPrimitives.add({
                //.toFixed(1)
                // id: '目标 simpleship' + j + ";" + oneship.position.x + ";" + oneship.position.y,
                //标注文字描述在此
                //pinBuilderl.fromText(url, descrarr[0] + '\n' + descrarr[1] + '\n' + descrarr[2] + '\n' + '船国家:香港' + '\n' + '船类型:', Cesium.Color.SALMON, 300),
                //  id: 'roundship' + j + ";" + oneship.x + ";" + oneship.y + ';' + '船国家:香港' + ';' + '船类型:货船;',
                id:'roundobj' + j,
                descr: 'roundobj' + j + ";" + oneship.x + ";" + oneship.y + ";" + oneship.rotation+";"+"",
                alarmmsg: '',
                sponser: oneship.sponser,
                name: j,
                sno: j,
                entitytype: 'roundobj',
                x: oneship.x,
                y: oneship.y,
                direction: oneship.rotation,
                pixelSize: 13,
                color: outlineColor,
                outlineColor: oneship.outlineColor.withAlpha(0.9),
                outlineWidth:  0 ,
                rotation: oneship.rotation,
                position: oneship.position


            });
            var onepoint = oneship
            // var inside_ball = pointPrimitives.add({
            //     //.toFixed(1)
            //     // id: '目标 simpleship' + j + ";" + oneship.position.x + ";" + oneship.position.y,
            //     //标注文字描述在此
            //     //pinBuilderl.fromText(url, descrarr[0] + '\n' + descrarr[1] + '\n' + descrarr[2] + '\n' + '船国家:香港' + '\n' + '船类型:', Cesium.Color.SALMON, 300),
            //     //  id: 'roundship' + j + ";" + oneship.x + ";" + oneship.y + ';' + '船国家:香港' + ';' + '船类型:货船;',
            //     id: 'roundship' + j + ";" + onepoint.x + ";" + onepoint.y + ";" + onepoint.rotation,
            //     name: j,
            //     sno: j,
            //     entitytype: 'roundship',
            //     x: onepoint.x,
            //     y: onepoint.y,
            //     direction: onepoint.rotation,
            //     pixelSize: 6,
            //     color: outlineColor,
            //     outlineColor: outlineColor,
            //     outlineWidth: 0,
            //     rotation: onepoint.rotation,
            //     position: onepoint.position


            // });
            swaparr[j].myball = ball
           // swaparr_inside[j].myball = inside_ball
        }
        //小于比例尺5公里，直接切换
        if (myviewer.scene.globe_has_swaptedToTriangle) {
            alert('should be swaped')
            var vp = new Cesium.Viewport()
            var w0 = 0;
            var h0 = 0;
            var w1 = myviewer.scene.canvas.clientWidth;
            //  w1 += Math.abs(dragedlen);
            var h1 = myviewer.scene.canvas.clientHeight;
            var currscene = myviewer.scene
                //   var movedRect = vp.getCurrCameraViewPortRealUg(w0, h0, w1, h1, currscene)
            var movedRect = null
                // var gsh = new Cesium.g_ships(myviewer)
                // var tsh = new Cesium.t_ships(myviewer)
            var msh = new Cesium.tmodel_ships(myviewer, myPolylinesCollection)
            // swapedAmt += msh.swaptoTriangleShip_leftup(polygon_billboards, color,
            //         swaparr, CylinderShipArr, swapcount, movedRect, view_angle_rate_left)
            //     //   this.swaptoPolygonShip(myviewer, color, swaparr, swapcount)
            // document.getElementById("swap_amt").innerHTML = CylinderShipArr.length;
            // swap = 0

        }

    };

    this.flytohere  = function() {
            //  Sandcastle.declare(flyInACity);

            var camera = myviewer.scene.camera;
           // var initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(0.0, 0.0, 90.0);

            camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(105.47, 33.23, 200000.0),
                // complete: function() {
                //     setTimeout(function() { //116  39
                //         camera.flyTo({
                //             destination: Cesium.Cartesian3.fromDegrees(116.47, 39.23, 200000.0),
                //             orientation: {
                //                 //   heading: Cesium.Math.toRadians(200.0),
                //                 //   pitch: Cesium.Math.toRadians(-50.0)
                //                 heading: initialOrientation.heading,
                //                 pitch: initialOrientation.pitch,
                //                 roll: initialOrientation.roll
                //             },
                //             easingFunction: Cesium.EasingFunction.LINEAR_NONE
                //         });
                //     }, 0);
                // }
            });
        }
     
  
}

//应用部分
// 爱厦门
// let logging = document.getElementById('logging');
let myapp
let mytimer
 //     //  url: 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
  // url: "http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
        //     // url: 'http://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7',

function initTiandimap(){

}
function initGdmap() {
    var map = new window.AMap.Map('gdmapDiv', {
        mapStyle: 'amap://styles/b03251066aef12c67115351079edd297'
    })
    map.setMapStyle('amap://styles/b03251066aef12c67115351079edd297')
    console.log(map)
}

function initApp() {
    myapp = new MainApp()
    myapp.init()
//  //   myapp.initMainChinaCity()
   // myapp.swapToSmall()
  //  myapp.addCicle()
    myapp.flytohere()
    $("#frontDatetimep").jqxDateTimeInput({
        width: 220,
        height: 25,
        formatString: 'yyyy/MM/dd   HH:mm',
        showTimeButton: true
    });
    $("#behindDatetimep").jqxDateTimeInput({
        width: 220,
        height: 25,
        formatString: 'yyyy/MM/dd   HH:mm',
        showTimeButton: true
    });
        var select_vediospeed = document.getElementById("select_vediospeed").value;
    var iTimeStep = select_vediospeed;
    //iTimerStep  iPlayTimeStep
    // API_SetPlayHistoryTrackTimeStep(iTimeStep);
    test_addequipment() //启动websocket监听
    return myapp
}
function addshipsHighSpeed() {
    myapp.delAlarm()
    myapp.initRoundShips() //初始化5万球形目标
    myapp.addShipHighspeed()
}
function stopstartLoop(){
  myapp.stopLoop()
}
function replay(type) {

    if (document.getElementById("ShowPlayShipTrackDiv").style.display == "block") {
        alert("当前正在回放轨迹，不能重复演示。");
        return;
    }
    document.getElementById("ShowPlayShipTrackDiv").style.display = "block"
}
function uncheckOtherRadio(id) {

}
function objStartAlram(){
    var show = true
    if(typeof(mytimer)!=undefined){
        window.clearInterval(mytimer);
    }
   
    myapp.delAlarm()
    
    mytimer=  setInterval(function(){
        if(show){
            myapp.showAlarm()
            show=false
        } else {
            myapp.delAlarm()
            show=true
        }
    }, 1000)
}

  /*
 setTimeout的作用是将代码推迟到指定时间执行，如果指定时间为0，
 setTimeout(f,0)那么会立刻执行吗？

答案是不会，因为setTimeout的机制是等到当前脚本的同步任务和“任务队列”中已有的事件，
全部处理完以后，才会执行setTimeout指定的任务，也就是说，setTimeout的真正作用是，
在“消息队列”的现有消息的后面再添加一个消息，规定在指定的时间执行某段代码，
setTimeout添加的事件，会在下一次等待和发送消息和事件时执行。
 
下面这段代码输出？
for(var i=0;i<5;i++){
    setTimeout(function(){
         console.log('delayer:' + i );//只不过是输出了5次最后i的值而已
    }, 0);//由于函数在最后执行，此时i的值已经改变了
    console.log(i);
}
 上面的代码输出结果为：

 0
1
2
3
4
delayer: 5
delayer: 5
delayer: 5
delayer: 5
delayer: 5

如果用闭包来实现：
for(var i=0;i<5;i++){
    setTimeout((function(){
        var n=i;
        return function(){
         return console.log('delayer:' + n );}
    })(), 0);
    console.log(i);
}
 */

   
